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

const prisma = new PrismaClient();

// GET /api/storefront/collections/featured
export const getFeaturedCollections = async (req: Request, res: Response) => {
  try {
    const collections = await prisma.featuredCollection.findMany({
      where: { active: true },
      orderBy: { order: 'asc' },
      include: {
        product: {
          select: {
            name: true,
            slug: true,
            price: true,
            images: true, // Assuming this is string[]
            category: { select: { slug: true } }
          }
        }
      }
    });

    // Transform to match the UI structure
    const formattedData = collections.map(item => {
      // Safety check in case product was deleted but relation persists (though Cascade handles this)
      if (!item.product) return null;

      return {
        id: item.id,
        title: item.title, // The custom label from FeaturedCollection
        productName: item.product.name, // The actual product name
        // Format price (assuming INR based on previous context)
        subtitle: `$ ${Number(item.product.price).toLocaleString('en-US')}`, 
        image: item.product.images[0] || '/placeholder.jpg',
        // Construct link: /category-slug/product-slug
        link: `/${item.product.category.slug}/${item.product.slug}` 
      };
    }).filter(Boolean); // Remove nulls

    res.json(formattedData);
  } catch (error) {
    console.error("Featured Collections Error:", error);
    res.status(500).json({ error: "Failed to fetch featured collections" });
  }
};

// POST /api/admin/featured
export const createFeaturedItem = async (req: Request, res: Response) => {
  try {
    const { title, productId, order, active } = req.body;

    if (!title || !productId) {
      return res.status(400).json({ error: "Title and Product are required" });
    }

    const newItem = await prisma.featuredCollection.create({
      data: {
        title,
        productId,
        order: parseInt(order) || 0,
        active: active !== undefined ? active : true
      }
    });

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

// PUT /api/admin/featured/:id
export const updateFeaturedItem = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { title, productId, order, active } = req.body;

    const updated = await prisma.featuredCollection.update({
      where: { id },
      data: {
        title,
        productId,
        order: parseInt(order),
        active
      }
    });

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

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