"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.updateStock = exports.getInventory = void 0;
const client_1 = require("@prisma/client");
const prisma = new client_1.PrismaClient();
// GET /api/admin/inventory
const getInventory = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { search, lowStock } = req.query;
        const whereClause = {};
        // 1. Search Logic (by SKU or Product Name)
        if (search) {
            whereClause.OR = [
                { sku: { contains: String(search), mode: 'insensitive' } },
                {
                    product: {
                        name: { contains: String(search), mode: 'insensitive' },
                    },
                },
            ];
        }
        // 2. Low Stock Filter (e.g., less than 10 units)
        if (lowStock === 'true') {
            whereClause.stock = { lte: 5 }; // You can make this threshold dynamic
        }
        // 3. Fetch Variants with Product Details
        const inventory = yield prisma.productVariant.findMany({
            where: whereClause,
            include: {
                product: {
                    select: {
                        name: true,
                        images: true, // Fetch images if you want to show thumbnails
                    },
                },
            },
            orderBy: { stock: 'asc' }, // Show low stock items first by default
        });
        // 4. Format for UI
        const formattedInventory = inventory.map((item) => {
            let status = 'In Stock';
            if (item.stock === 0)
                status = 'Out of Stock';
            else if (item.stock <= 5)
                status = 'Low Stock';
            return {
                id: item.id,
                sku: item.sku,
                product: item.product.name,
                // image: item.product.images[0] || null, // Optional
                size: item.size,
                color: item.color,
                stock: item.stock,
                status: status,
            };
        });
        res.json(formattedInventory);
    }
    catch (error) {
        console.error('Get Inventory Error:', error);
        res.status(500).json({ error: 'Failed to fetch inventory' });
    }
});
exports.getInventory = getInventory;
// PUT /api/admin/inventory/:id
const updateStock = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id } = req.params;
        const { type, quantity, reason } = req.body; // type: 'add' | 'remove'
        if (!quantity || quantity <= 0) {
            return res.status(400).json({ error: 'Valid quantity is required' });
        }
        // 1. Fetch current variant to check stock
        const variant = yield prisma.productVariant.findUnique({
            where: { id },
        });
        if (!variant)
            return res.status(404).json({ error: 'Variant not found' });
        let newStock = variant.stock;
        // 2. Calculate new stock
        if (type === 'add') {
            newStock += Number(quantity);
        }
        else if (type === 'remove') {
            if (variant.stock < quantity) {
                return res.status(400).json({ error: 'Insufficient stock to remove' });
            }
            newStock -= Number(quantity);
        }
        else {
            return res.status(400).json({ error: "Invalid operation type. Use 'add' or 'remove'." });
        }
        // 3. Update Database
        // Note: In a real production app, you would also create a 'InventoryLog' entry here 
        // to track WHO changed it and WHY (the 'reason' field).
        const updatedVariant = yield prisma.productVariant.update({
            where: { id },
            data: { stock: newStock },
            include: { product: { select: { name: true } } }
        });
        res.json({
            message: 'Stock updated successfully',
            stock: updatedVariant.stock,
            product: updatedVariant.product.name
        });
    }
    catch (error) {
        console.error('Update Stock Error:', error);
        res.status(500).json({ error: 'Failed to update stock' });
    }
});
exports.updateStock = updateStock;
