import { Request, Response } from 'express';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

// GET /api/admin/categories
export const getCategories = async (req: Request, res: Response) => {
  try {
    const categories = await prisma.category.findMany({
      include: {
        parent: {
          select: { name: true }, // Fetch parent name to display in table
        },
        _count: {
          select: { products: true }, // Count products in this category
        },
      },
      orderBy: { createdAt: 'desc' },
    });

    // Format for UI
    const formattedCategories = categories.map((cat) => ({
      id: cat.id,
      name: cat.name,
      slug: cat.slug,
      description: cat.description,
      parentId: cat.parentId,
      parentName: cat.parent ? cat.parent.name : '-', // Display '-' if top level
      count: cat._count.products,
    }));

    res.json(formattedCategories);
  } catch (error) {
    console.error('Get Categories Error:', error);
    res.status(500).json({ error: 'Failed to fetch categories' });
  }
};

// POST /api/admin/categories
export const createCategory = async (req: Request, res: Response) => {
  try {
    const { name, slug, parentId, description } = req.body;

    // Basic Validation
    if (!name || !slug) {
      return res.status(400).json({ error: 'Name and Slug are required' });
    }

    // Handle "None" parent (empty string or "none")
    const cleanParentId = parentId && parentId !== 'none' ? parentId : null;

    const newCategory = await prisma.category.create({
      data: {
        name,
        slug,
        description,
        parentId: cleanParentId,
      },
    });

    res.status(201).json(newCategory);
  } catch (error: any) {
    console.error('Create Category Error:', error);
    // Handle Unique Constraint Violation (Duplicate Slug)
    if (error.code === 'P2002') {
      return res.status(409).json({ error: 'A category with this slug already exists.' });
    }
    res.status(500).json({ error: 'Failed to create category' });
  }
};

// PUT /api/admin/categories/:id
export const updateCategory = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { name, slug, parentId, description } = req.body;

    const cleanParentId = parentId && parentId !== 'none' ? parentId : null;

    // Prevent a category from being its own parent
    if (cleanParentId === id) {
       return res.status(400).json({ error: 'A category cannot be its own parent.' });
    }

    const updatedCategory = await prisma.category.update({
      where: { id },
      data: {
        name,
        slug,
        description,
        parentId: cleanParentId,
      },
    });

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

// DELETE /api/admin/categories/:id
export const deleteCategory = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;

    // Check if category has children or products before deleting
    // (Optional safety check, or let Prisma foreign key constraints handle it)
    const categoryToCheck = await prisma.category.findUnique({
      where: { id },
      include: { _count: { select: { products: true, children: true } } },
    });

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

    if (categoryToCheck._count.children > 0) {
      return res.status(400).json({ error: 'Cannot delete: This category has sub-categories.' });
    }

    // Optional: Prevent deleting if it has products, or just allow it and products become uncategorized
    if (categoryToCheck._count.products > 0) {
       // Decide logic here. For now, strict mode:
       return res.status(400).json({ error: 'Cannot delete: This category contains products.' });
    }

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

    res.json({ message: 'Category deleted successfully' });
  } catch (error) {
    console.error('Delete Category Error:', error);
    res.status(500).json({ error: 'Failed to delete category' });
  }
};