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

// 1. CREATE: Initialize or forcefully overwrite a stock balance row record
router.post('/', async (req, res) => {
    const { productId, available, sold } = req.body;
    
    if (!productId) {
        return res.status(400).json({ error: "Product specification ID parameter missing." });
    }

    try {
        // Enforce safe numerical parsing before insertion
        const parsedAvailable = parseInt(available, 10) || 0;
        const parsedSold = parseInt(sold, 10) || 0;

        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 });
    }
});

// 2. READ: Dynamic Left Join mapping layout safely passing structural rows to React UI
router.get('/', async (req, res) => {
    try {
        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`
        );

        // Map values clearly so they never fall back to undefined or break React components
        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: "Database query optimization breakdown: " + err.message });
    }
});

// 3. UPDATE: Modify existing parameters using row ID indicators 
router.put('/:id', async (req, res) => {
    const stockId = req.params.id;
    const { available, sold } = req.body;
    
    try {
        const parsedAvailable = parseInt(available, 10) || 0;
        const parsedSold = parseInt(sold, 10) || 0;

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

// 4. DELETE: Drop tracking row instance manually out of the system layout registry
router.delete('/:id', async (req, res) => {
    const stockId = req.params.id;
    try {
        await db.query('DELETE FROM stock_status WHERE stock_id = ?', [stockId]);
        res.json({ message: "Stock tracking parameters dropped." });
    } catch (err) {
        res.status(500).json({ error: "Stock destruction failure: " + err.message });
    }
});

module.exports = router;