const express = require('express');
const router = express.Router();
const db = require('../config/db');

// --------------------------------------------------------------------
// READ: Fetch master product catalog data matrix stream
// FIXES: 404 error by mapping both base path and legacy /list alias
// --------------------------------------------------------------------
router.get(['/', '/list'], async (req, res) => {
    try {
        const [rows] = await db.query('SELECT * FROM products ORDER BY product_id DESC');
        
        // Map fields cleanly to match lower_case naming conventions inside your UI components
        const formatted = rows.map(p => ({
            product_id: p.product_id,
            product_name: p.ProductName,
            category: p.Category,
            quantity: p.Quantity,
            unit_price: parseFloat(p.UnitPrice) || 0,
            total_price: parseFloat(p.TotalPrice) || 0
        }));
        
        res.json(formatted);
    } catch (err) {
        res.status(500).json({ error: "Failed to load master products catalog stream: " + err.message });
    }
});

// --------------------------------------------------------------------
// CREATE: Save Product and link/insert its available quantity into stock_status instantly
// --------------------------------------------------------------------
router.post('/', async (req, res) => {
    const { name, category, price, quantity } = req.body;
    
    // Safety check block to avoid database constraint validation crashes
    if (!name || !category) {
        return res.status(400).json({ error: "Missing required core product metadata parameters." });
    }

    const connection = await db.getConnection(); // Get atomic transactional link
    try {
        await connection.beginTransaction();

        // 1. Insert product catalog entry - Using exact Database Casing
        const [prodResult] = await connection.query(
            'INSERT INTO products (ProductName, Category, UnitPrice, Quantity) VALUES (?, ?, ?, ?)',
            [name, category, parseFloat(price) || 0.00, parseInt(quantity, 10) || 0]
        );
        const newProductId = prodResult.insertId;

        // 2. Automatically link its initial available quantity in stock tracking layout
        // Columns map exactly to: AvailableQuantity, SoldQuantity
        await connection.query(
            'INSERT INTO stock_status (product_id, AvailableQuantity, SoldQuantity) VALUES (?, ?, 0)',
            [newProductId, parseInt(quantity, 10) || 0]
        );

        await connection.commit();
        res.status(201).json({ message: "Product and initial stock inventory registered." });
    } catch (err) {
        await connection.rollback();
        res.status(500).json({ error: err.message });
    } finally {
        connection.release();
    }
});

// --------------------------------------------------------------------
// UPDATE: Update product attributes AND modify available quantity tracking parameter
// --------------------------------------------------------------------
router.put('/:id', async (req, res) => {
    const { name, category, price, quantity } = req.body;
    const productId = req.params.id;
    const connection = await db.getConnection();
    try {
        await connection.beginTransaction();

        // 1. Update product master fields - Using exact Database Casing
        await connection.query(
            'UPDATE products SET ProductName = ?, Category = ?, UnitPrice = ?, Quantity = ? WHERE product_id = ?',
            [name, category, parseFloat(price) || 0.00, parseInt(quantity, 10) || 0, productId]
        );

        // 2. Update or insert matching quantity status limits dynamically
        // Columns map exactly to: AvailableQuantity, SoldQuantity
        const targetQty = parseInt(quantity, 10) || 0;
        await connection.query(
            `INSERT INTO stock_status (product_id, AvailableQuantity, SoldQuantity) 
             VALUES (?, ?, 0) 
             ON DUPLICATE KEY UPDATE AvailableQuantity = ?`,
            [productId, targetQty, targetQty]
        );

        await connection.commit();
        res.json({ message: "Product and matching stock counts modified successfully." });
    } catch (err) {
        await connection.rollback();
        res.status(500).json({ error: err.message });
    } finally {
        connection.release();
    }
});

module.exports = router;