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

// --------------------------------------------------------------------
// READ: Stock Status Tracker using robust LEFT JOIN alignments
// --------------------------------------------------------------------
router.get('/', async (req, res) => {
    try {
        // Aligned all table variables to match exact schema casing
        // Kept lowercase aliases so your React UI mapping arrays don't have to change!
        const [rows] = await db.query(
            `SELECT 
                p.product_id, 
                p.ProductName AS product_name, 
                p.Category AS category,
                p.UnitPrice AS unit_price,
                COALESCE(s.stock_id, 0) AS stock_id,
                COALESCE(s.AvailableQuantity, p.Quantity) AS stored_quantity, 
                COALESCE(s.SoldQuantity, 0) AS sold_quantity
             FROM products p
             LEFT JOIN stock_status s ON p.product_id = s.product_id
             ORDER BY p.product_id DESC`
        );

        // Inject the precise remaining calculations to match your frontend expectation schema
        const formattedData = rows.map(item => ({
            product_id: item.product_id,
            product_name: item.product_name,
            category: item.category,
            unit_price: parseFloat(item.unit_price) || 0,
            stock_id: item.stock_id,
            stored_quantity: parseInt(item.stored_quantity, 10) || 0,
            sold_quantity: parseInt(item.sold_quantity, 10) || 0,
            remaining_quantity: (parseInt(item.stored_quantity, 10) || 0) - (parseInt(item.sold_quantity, 10) || 0)
        }));

        res.json(formattedData);
    } catch (err) {
        res.status(500).json({ error: "Stock status fetch breakdown: " + err.message });
    }
});

// --------------------------------------------------------------------
// CREATE: Save Stock Record or handle duplicate keys gracefully
// --------------------------------------------------------------------
router.post('/', async (req, res) => {
    const { productId, available, sold } = req.body;
    
    if (!productId) {
        return res.status(400).json({ error: "Missing Target Product Identifier parameter." });
    }

    // Explicit type casing validation layer
    const parsedAvailable = parseInt(available, 10) || 0;
    const parsedSold = parseInt(sold, 10) || 0;

    try {
        // Updated columns to match schema requirements: AvailableQuantity, SoldQuantity
        await db.query(
            `INSERT INTO stock_status (product_id, AvailableQuantity, SoldQuantity) 
             VALUES (?, ?, ?)
             ON DUPLICATE KEY UPDATE AvailableQuantity = ?, SoldQuantity = ?`, 
            [productId, parsedAvailable, parsedSold, parsedAvailable, parsedSold]
        );
        res.status(201).json({ message: "Stock parameters initialized successfully." });
    } catch (err) {
        res.status(500).json({ error: "Stock insertion breakdown: " + err.message });
    }
});

// --------------------------------------------------------------------
// UPDATE: Modify parameters using row ID indicators
// --------------------------------------------------------------------
router.put('/:id', async (req, res) => {
    const { available, sold } = req.body;
    
    // Explicit numeric sanitation to guard backend storage paths
    const parsedAvailable = parseInt(available, 10) || 0;
    const parsedSold = parseInt(sold, 10) || 0;

    try {
        // Updated columns to target: AvailableQuantity, SoldQuantity
        await db.query(
            'UPDATE stock_status SET AvailableQuantity = ?, SoldQuantity = ? WHERE stock_id = ?', 
            [parsedAvailable, parsedSold, req.params.id]
        );
        res.json({ message: "Stock adjustments updated successfully." });
    } catch (err) {
        res.status(500).json({ error: "Stock modification failure: " + err.message });
    }
});

// --------------------------------------------------------------------
// DELETE: Remove tracking instance from registry
// --------------------------------------------------------------------
router.delete('/:id', async (req, res) => {
    try {
        await db.query('DELETE FROM stock_status WHERE stock_id = ?', [req.params.id]);
        res.json({ message: "Stock parameters removed." });
    } catch (err) {
        res.status(500).json({ error: "Stock destruction failure: " + err.message });
    }
});

module.exports = router;