import { db } from "@/helpers/api";

export default async function handler(req, res) {
    if (req.method !== "POST") {
        return res.status(405).json({ success: false, error: "Method not allowed" });
    }

    await db.initialize(); // obligatoriu

    const { categoryId, supplier, margin, overrideIndividual, categoryLevel } = req.body;

    if (!categoryId || !supplier || margin === undefined || margin === null) {
        return res.status(400).json({ success: false, error: "Date lipsă" });
    }

    const marginColumn = supplier === "AVEX" ? "margin_avex" : "margin_depox";
    const marginValue = parseFloat(margin);

    try {
        // 1. Salvează marja în tabelul categorii
        await db.sequelize.query(
            `UPDATE categories SET ${marginColumn} = ? WHERE id = ?`,
            { replacements: [marginValue, categoryId] }
        );

        // 2. Găsește categoria
        const [categoryRows] = await db.sequelize.query(
            `SELECT name, slug FROM categories WHERE id = ?`,
            { replacements: [categoryId] }
        );
        const category = categoryRows[0];
        if (!category) {
            return res.status(404).json({ success: false, error: "Categoria nu a fost găsită" });
        }

        // 3. Fetch prețuri achiziție
        let acquisitionPrices = {};

        if (supplier === "DEPOX") {
            const feedRes = await fetch("https://easy-sales.com/feed/445/975393179/okazii.xml");
            const xmlText = await feedRes.text();
            const auctionRegex = /<AUCTION>([\s\S]*?)<\/AUCTION>/g;
            let match;
            while ((match = auctionRegex.exec(xmlText)) !== null) {
                const block = match[1];
                const skuMatch = block.match(/<SKU>([^<]*)<\/SKU>/);
                const priceMatch = block.match(/<PRICE>([^<]*)<\/PRICE>/);
                const discountMatch = block.match(/<DISCOUNT_PRICE>([^<]*)<\/DISCOUNT_PRICE>/);
                if (skuMatch && priceMatch) {
                    const sku = skuMatch[1].trim();
                    const price = parseFloat(priceMatch[1]);
                    const discount = parseFloat(discountMatch?.[1] || 0);
                    acquisitionPrices[sku] = discount > 0 && discount < price ? discount : price;
                }
            }
        }

        // 4. Găsește produsele din categorie
        const col = categoryLevel || "categoryName";

        let productsSQL = `SELECT id, sku, price FROM products WHERE ${col} = ? AND back_supplier = ?`;
        const replacements = [category.name, supplier];

        if (!overrideIndividual) {
            productsSQL += ` AND priceReduced IS NULL`;
        }

        const [products] = await db.sequelize.query(productsSQL, { replacements });

        if (products.length === 0) {
            return res.status(200).json({
                success: true,
                message: `Marja salvată. Nu s-au găsit produse de actualizat.`,
                updatedCount: 0,
                totalFound: 0,
            });
        }

        // 5. Actualizează prețurile
        let updatedCount = 0;
        let errors = [];

        for (const product of products) {
            try {
                let acquisitionPrice = null;

                if (supplier === "DEPOX") {
                    acquisitionPrice = acquisitionPrices[product.sku?.trim()];
                } else if (supplier === "AVEX") {
                    const avexRes = await fetch(
                        `${process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3000"}/api/admin/avex/profit?sku=${encodeURIComponent(product.sku)}`
                    );
                    const avexData = await avexRes.json();
                    if (avexData.success) {
                        acquisitionPrice = parseFloat(avexData.data.price);
                    }
                }

                if (!acquisitionPrice || isNaN(acquisitionPrice)) {
                    errors.push(`SKU ${product.sku}: preț achiziție negăsit`);
                    continue;
                }

                const newPrice = acquisitionPrice * (1 + marginValue / 100);

                await db.sequelize.query(
                    `UPDATE products SET price = ? WHERE id = ?`,
                    { replacements: [newPrice.toFixed(2), product.id] }
                );
                updatedCount++;
            } catch (err) {
                errors.push(`SKU ${product.sku}: ${err.message}`);
            }
        }

        return res.status(200).json({
            success: true,
            message: `Marjă salvată și ${updatedCount} produse actualizate.`,
            updatedCount,
            totalFound: products.length,
            errors: errors.length > 0 ? errors : undefined,
        });

    } catch (err) {
        console.error("Eroare margin categorie:", err);
        return res.status(500).json({ success: false, error: err.message });
    }
}