"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.deleteProduct = exports.updateProduct = exports.getProductDetails = exports.createProduct = exports.getProducts = void 0;
const client_1 = require("@prisma/client");
const r2_1 = require("../../utils/r2");
const prisma = new client_1.PrismaClient();
// GET /api/products
// Supports filtering by Category, Search, and Status
const getProducts = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { search, categoryId, status } = req.query;
        const whereClause = {};
        // 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 = yield 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" });
    }
});
exports.getProducts = getProducts;
// POST /api/products
const createProduct = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { name, slug, description, price, compareAtPrice, categoryId, tags, details, isFeatured } = req.body;
        // 🔥 FILES → URL ARRAY
        const files = req.files;
        if (!files || files.length === 0) {
            return res.status(400).json({ error: "Product images are required" });
        }
        // Upload all images to R2
        const imageUrls = yield Promise.all(files.map(file => (0, r2_1.uploadFileToR2)(file).then(r => r.url)));
        const product = yield 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) {
        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" });
    }
});
exports.createProduct = createProduct;
// GET /api/products/:id
const getProductDetails = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id } = req.params;
        const product = yield 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" });
    }
});
exports.getProductDetails = getProductDetails;
// PUT /api/products/:id
const updateProduct = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    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 = yield 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" });
    }
});
exports.updateProduct = updateProduct;
// DELETE /api/products/:id
const deleteProduct = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id } = req.params;
        // Check if product exists
        const product = yield prisma.product.findUnique({ where: { id } });
        if (!product)
            return res.status(404).json({ error: "Product not found" });
        // Delete product
        yield 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" });
    }
});
exports.deleteProduct = deleteProduct;
