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

// --------------------------------------------------------------------
// CREATE: Log Transaction and adapt dynamic warehouse stock metrics
// PROTECTS: Avoids 400 Bad Requests by parsing multiple request structures
// --------------------------------------------------------------------
router.post('/', async (req, res) => {
    // Destructure flexible property alternatives from incoming payload
    const productId = parseInt(req.body.productId || req.body.product_id, 10);
    const qty = req.body.qty || req.body.sold_quantity || req.body.SoldQuantity;
    const price = req.body.price || req.body.sold_unit_price || req.body.SoldUnitPrice;
    const date = req.body.date || req.body.sales_date || req.body.SalesDate || new Date().toISOString().split('T')[0];

    const numericQty = parseInt(qty, 10);
    const numericPrice = parseFloat(price);

    // Explicit validation checklist to protect against database constraints
    if (!productId || isNaN(numericQty) || numericQty <= 0 || isNaN(numericPrice) || numericPrice <= 0) {
        return res.status(400).json({ error: "Invalid operational payload parameter structures provided." });
    }

    const connection = await db.getConnection(); // Use dedicated connection for atomic transactions
    try {
        await connection.beginTransaction();

        // 1. Evaluate current stock profile parameters from database context
        const [stockCheck] = await connection.query(
            'SELECT stock_id, AvailableQuantity, SoldQuantity FROM stock_status WHERE product_id = ?',
            [productId]
        );

        if (stockCheck.length > 0) {
            const currentAvailable = parseInt(stockCheck[0].AvailableQuantity, 10) || 0;
            const currentSold = parseInt(stockCheck[0].SoldQuantity, 10) || 0;
            const liveRemainingStock = currentAvailable - currentSold;

            // Reject transaction instantly if demand exceeds actual available warehouse units
            if (numericQty > liveRemainingStock) {
                await connection.rollback();
                return res.status(400).json({ 
                    error: `Transaction blocked! Requested amount exceeds current available balance (${liveRemainingStock} left).` 
                });
            }

            // Update running sold metrics column target increment
            await connection.query(
                'UPDATE stock_status SET SoldQuantity = SoldQuantity + ? WHERE product_id = ?',
                [numericQty, productId]
            );
        } else {
            // Fetch initial product threshold value to set base AvailableQuantity correctly
            const [productRow] = await connection.query(
                'SELECT Quantity FROM products WHERE product_id = ?',
                [productId]
            );
            const baseQuantity = productRow.length > 0 ? parseInt(productRow[0].Quantity, 10) : numericQty;

            // Initialize a matching line row entry with true initial parameters
            await connection.query(
                'INSERT INTO stock_status (product_id, AvailableQuantity, SoldQuantity) VALUES (?, ?, ?)',
                [productId, baseQuantity, numericQty]
            );
        }

        // 2. Commit transaction record to sales ledger
        await connection.query(
            'INSERT INTO sales (product_id, SoldQuantity, SoldUnitPrice, SalesDate) VALUES (?, ?, ?, ?)', 
            [productId, numericQty, numericPrice, date]
        );

        await connection.commit();
        res.status(201).json({ message: "Sales entry logged and stock tracking updated successfully!" });
    } catch (err) {
        await connection.rollback();
        res.status(500).json({ error: "Sales router transaction execution failure: " + err.message });
    } finally {
        connection.release();
    }
});

// --------------------------------------------------------------------
// READ: Fetch sales report metrics
// --------------------------------------------------------------------
router.get('/daily-report', async (req, res) => {
    try {
        // Query database context for modern enterprise dashboard display structures
        const [rows] = await db.query(
            `SELECT 
                s.sales_id, 
                s.product_id,
                p.ProductName AS product_name, 
                s.SoldQuantity AS sold_quantity, 
                s.SoldUnitPrice AS sold_unit_price, 
                s.SoldTotalPrice AS sold_total_price, 
                s.SalesDate AS sales_date 
             FROM sales s 
             JOIN products p ON s.product_id = p.product_id 
             ORDER BY s.sales_id DESC`
        );
        res.json(rows);
    } catch (err) {
        res.status(500).json({ error: "Failed to load database sales report stream: " + err.message });
    }
});

module.exports = router;