"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteVariant = exports.updateVariant = exports.createProductVariant = void 0;
const client_1 = require("@prisma/client");
const prisma = new client_1.PrismaClient();
// POST /api/products/:productId/variants
const createProductVariant = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    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 = yield 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 = yield 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) {
        // 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" });
    }
});
exports.createProductVariant = createProductVariant;
// PUT /api/variants/:id
const updateVariant = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id } = req.params;
        const { stock, priceDiff, sku } = req.body;
        const variant = yield 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" });
    }
});
exports.updateVariant = updateVariant;
// DELETE /api/variants/:id
const deleteVariant = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id } = req.params;
        yield prisma.productVariant.delete({ where: { id } });
        res.json({ message: "Variant deleted" });
    }
    catch (error) {
        res.status(500).json({ error: "Failed to delete variant" });
    }
});
exports.deleteVariant = deleteVariant;
