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

const prisma = new PrismaClient();

// POST /api/products/:productId/variants
export const createProductVariant = async (req: Request, res: Response) => {
  try {
    const { productId } = req.params;
    const { size, color, stock, priceDiff, sku } = req.body;

    // Validate required fields
    if (!size || !color || !stock) {
      return res.status(400).json({ error: "Size, color, and stock are required" });
    }

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

    // Generate SKU if not provided
    const variantSku = sku || `${product.slug}-${size}-${color}`.toLowerCase().replace(/\s+/g, "-");

    // Create ProductVariant
    const variant = await prisma.productVariant.create({
      data: {
        productId,
        size,
        color,
        stock: Number(stock),
        priceDiff: priceDiff ? Number(priceDiff) : null,
        sku: variantSku,
      },
    });

    res.status(201).json({ success: true, variant });
  } catch (error: any) {
    // Handle unique constraint violations
    if (error.code === "P2002") {
      return res.status(400).json({ error: "Variant already exists (duplicate size/color or SKU)" });
    }

    console.error("Create ProductVariant Error:", error);
    res.status(500).json({ error: "Failed to create product variant" });
  }
};

// PUT /api/variants/:id
export const updateVariant = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { stock, priceDiff, sku } = req.body;

    const variant = await prisma.productVariant.update({
      where: { id },
      data: {
        stock: stock !== undefined ? parseInt(stock) : undefined,
        priceDiff: priceDiff !== undefined ? parseFloat(priceDiff) : undefined,
        sku: sku // Allow manual SKU override
      }
    });

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

// DELETE /api/variants/:id
export const deleteVariant = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    await prisma.productVariant.delete({ where: { id } });
    res.json({ message: "Variant deleted" });
  } catch (error) {
    res.status(500).json({ error: "Failed to delete variant" });
  }
};