import { Request, Response } from 'express';
import prisma from '../prisma/client';
import { CategoryType } from '../types/category.types';

// GET all categories


// export const getAllCategories = (req: Request, res: Response) => { res.send("Hello Kuriloo api category ") }


export const getAllCategories = async (req: Request, res: Response) => {
    try {
        const categories = await prisma.category.findMany();
        res.json(categories);
    } catch (error) {
        console.error('Error fetching categories:', error);
        res.status(500).json({ error: 'Failed to fetch categories' });
    }
};

// CREATE a new category
export const createCategory = async (req: Request, res: Response) => {
    try {
        const { category_name, status, tag }: CategoryType = req.body;

        const category = await prisma.category.create({
            data: {
                category_name,
                status,
                tag,
            },
        });

        res.status(201).json(category);
    } catch (error) {
        console.error('Error creating category:', error);
        res.status(500).json({ error: 'Failed to create category' });
    }
};

// UPDATE a category by ID
export const updateCategory = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const { category_name, status, tag }: Partial<CategoryType> = req.body;

        const existingCategory = await prisma.category.findUnique({
            where: { id: Number(id) },
        });

        if (!existingCategory) {
            return res.status(404).json({ error: 'Category not found' });
        }

        const updatedCategory = await prisma.category.update({
            where: { id: Number(id) },
            data: {
                category_name,
                status,
                tag,
            },
        });

        res.json(updatedCategory);
    } catch (error) {
        console.error('Error updating category:', error);
        res.status(500).json({ error: 'Failed to update category' });
    }
};

// DELETE a category by ID
export const deleteCategory = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;

        const existingCategory = await prisma.category.findUnique({
            where: { id: Number(id) },
        });

        if (!existingCategory) {
            return res.status(404).json({ error: 'Category not found' });
        }

        await prisma.category.delete({
            where: { id: Number(id) },
        });

        res.status(204).send(); // No Content
    } catch (error) {
        console.error('Error deleting category:', error);
        res.status(500).json({ error: 'Failed to delete category' });
    }
};
