import { Request, Response } from 'express';
import { PrismaClient } from '@prisma/client';
import ApiError from '../../utils/apiError';
import { uploadFileToR2 } from '../../utils/r2';

const prisma = new PrismaClient();

// GET /api/admin/bento
export const getBentoItems = async (req: Request, res: Response) => {
  try {
    const items = await prisma.featuredCategory.findMany({
      include: {
        category: {
          select: { name: true, image: true }
        }
      },
      orderBy: { order: 'asc' }
    });

    const formatted = items.map(item => ({
      id: item.id,
      categoryName: item.category?.name || "Unknown Category",
      // Priority: Custom Image -> Category Image -> Placeholder
      image: item.customImage || item.category?.image || '/placeholder-category.jpg',
      size: item.size,
      active: item.active,
      order: item.order,
      categoryId: item.categoryId,
      customImage: item.customImage // Include for edit form
    }));

    res.json(formatted);
  } catch (error) {
    console.error("Get Bento Error:", error);
    res.status(500).json({ error: "Failed to fetch grid items" });
  }
};

// POST /api/admin/bento
export const createBentoItem = async (req: Request, res: Response) => {
  try {
    const { categoryId, size, order, active } = req.body;

    if (!categoryId) {
      return res.status(400).json({ error: "Category is required" });
    }

    const image=req.file;
    if(!image){
      throw new ApiError(false,400,"Images is required")
    }

    const uploadedImg=await uploadFileToR2(image)

    if(!uploadedImg.url){
       throw new ApiError(false,400,"Image Upload to R2 Fail")
    }

    const newItem = await prisma.featuredCategory.create({
      data: {
        categoryId,
        size: size || 'small',
        customImage:uploadedImg.url,
        order: parseInt(order) || 0,
        active: active ==="true"
      }
    });

    res.status(201).json(newItem);
  } catch (error) {
    console.error("Create Bento Error:", error);
    res.status(500).json({ error: "Failed to create grid item" });
  }
};

// PUT /api/admin/bento/:id
export const updateBentoItem = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { categoryId, size, customImage, order,active } = req.body;

    const updated = await prisma.featuredCategory.update({
      where: { id },
      data: {
        categoryId,
        size,
        customImage,
        order: parseInt(order),
        active:active==="true",
      }
    });

    res.json(updated);
  } catch (error) {
    res.status(500).json({ error: "Failed to update grid item" });
  }
};

// DELETE /api/admin/bento/:id
export const deleteBentoItem = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    await prisma.featuredCategory.delete({ where: { id } });
    res.json({ message: "Item deleted" });
  } catch (error) {
    res.status(500).json({ error: "Failed to delete item" });
  }
};