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

const prisma = new PrismaClient();

// GET /api/products
// Supports filtering by Category, Search, and Status
export const getProducts = async (req: Request, res: Response) => {
  try {
    const { search, categoryId, status } = req.query;

    const whereClause: any = {};
    
    // Filter by Archive Status
    if (status === 'archived') whereClause.isArchived = true;
    else if (status === 'active') whereClause.isArchived = false;

    // Filter by Category
    if (categoryId) whereClause.categoryId = String(categoryId);

    // Search
    if (search) {
      whereClause.OR = [
        { name: { contains: String(search), mode: 'insensitive' } },
        { slug: { contains: String(search), mode: 'insensitive' } },
      ];
    }

    const products = await prisma.product.findMany({
      where: whereClause,
      include: {
        category: { select: { name: true } },
        variants: true, // Needed to calculate total stock
      },
      orderBy: { createdAt: 'desc' },
      take: 50
    });

    // Format for UI (Calculating total stock from variants)
    const formatted = products.map(p => {
      // Calculate total stock from variants
      const totalStock = p.variants.reduce((sum, v) => sum + v.stock, 0);
      
      return {
        id: p.id,
        name: p.name,
        slug: p.slug,
        image: p.images[0] || null, // Main image
        price: Number(p.price),
        stock: totalStock, // Dynamic stock based on variants
        category: p.category.name,
        status: p.isArchived ? 'Archived' : 'Active',
        variantCount: p.variants.length
      };
    });

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

// POST /api/products
export const createProduct = async (req: Request, res: Response) => {
  try {
    const {
      name,
      slug,
      description,
      price,
      compareAtPrice,
      categoryId,
      tags,
      details,
      isFeatured
    } = req.body;

    // 🔥 FILES → URL ARRAY
    const files = req.files as Express.Multer.File[];

    if (!files || files.length === 0) {
      return res.status(400).json({ error: "Product images are required" });
    }

    // Upload all images to R2
    const imageUrls = await Promise.all(
      files.map(file => uploadFileToR2(file).then(r => r.url))
    );

    const product = await prisma.product.create({
      data: {
        name,
        slug,
        description,
        details,
        price: Number(price),
        compareAtPrice: Number(compareAtPrice) || 0,
        categoryId,

        images: imageUrls, // ✅ ARRAY

        tags: tags ? JSON.parse(tags) : [],
        isFeatured: isFeatured === "true",
        isArchived: false
      }
    });

    return res.status(201).json(product);
  } catch (error: any) {
    if (error.code === "P2002") {
      return res.status(400).json({ error: "Product slug must be unique" });
    }

    console.error(error);
    return res.status(500).json({ error: "Failed to create product" });
  }
};


// GET /api/products/:id
export const getProductDetails = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const product = await prisma.product.findUnique({
      where: { id },
      include: {
        category: true,
        variants: true
      }
    });

    if (!product) return res.status(404).json({ error: "Product not found" });
    res.json(product);
  } catch (error) {
    res.status(500).json({ error: "Failed to fetch details" });
  }
};

// PUT /api/products/:id
export const updateProduct = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const data = req.body;

    // Separate variant data if passed (variants should ideally be handled by variant controller)
    // Here we update core product info
    const product = await prisma.product.update({
      where: { id },
      data: {
        name: data.name,
        description: data.description,
        price: data.price,
        compareAtPrice: data.compareAtPrice,
        images: data.images,
        tags: data.tags,
        isFeatured: data.isFeatured,
        isArchived: data.isArchived,
        categoryId: data.categoryId
      }
    });

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





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

    // Check if product exists
    const product = await prisma.product.findUnique({ where: { id } });
    if (!product) return res.status(404).json({ error: "Product not found" });

    // Delete product
    await prisma.product.delete({ where: { id } });

    res.json({ success: true, message: "Product deleted successfully" });
  } catch (error) {
    console.error("Delete Product Error:", error);
    res.status(500).json({ error: "Failed to delete product" });
  }
};