const express = require('express');
const pool = require('../config/db');
const authMiddleware = require('../middleware/auth');

const router = express.Router();

function getDateRange(period) {
  const today = new Date();
  const endDate = today.toISOString().split('T')[0];
  let startDate;

  if (period === 'daily') {
    startDate = endDate;
  } else if (period === 'weekly') {
    const weekAgo = new Date(today);
    weekAgo.setDate(weekAgo.getDate() - 7);
    startDate = weekAgo.toISOString().split('T')[0];
  } else if (period === 'monthly') {
    const monthAgo = new Date(today);
    monthAgo.setMonth(monthAgo.getMonth() - 1);
    startDate = monthAgo.toISOString().split('T')[0];
  } else {
    return null;
  }

  return { startDate, endDate };
}

router.get('/:period', authMiddleware, async (req, res) => {
  try {
    const { period } = req.params;
    const range = getDateRange(period);

    if (!range) {
      return res.status(400).json({ message: 'Invalid period. Use daily, weekly, or monthly.' });
    }

    const { startDate, endDate } = range;

    const [availableStock] = await pool.query(`
      SELECT productCode, productName, category, quantityInStock, unitPrice, supplierName
      FROM Product
      ORDER BY productCode
    `);

    const [stockIn] = await pool.query(`
      SELECT st.transactionId, st.transactionDate, st.quantityMoved, st.productCode,
             p.productName, w.warehouseName
      FROM StockTransaction st
      JOIN Product p ON st.productCode = p.productCode
      JOIN Warehouse w ON st.warehouseCode = w.warehouseCode
      WHERE st.transactionType = 'IN'
        AND st.transactionDate BETWEEN ? AND ?
      ORDER BY st.transactionDate DESC
    `, [startDate, endDate]);

    const [stockOut] = await pool.query(`
      SELECT st.transactionId, st.transactionDate, st.quantityMoved, st.productCode,
             p.productName, w.warehouseName
      FROM StockTransaction st
      JOIN Product p ON st.productCode = p.productCode
      JOIN Warehouse w ON st.warehouseCode = w.warehouseCode
      WHERE st.transactionType = 'OUT'
        AND st.transactionDate BETWEEN ? AND ?
      ORDER BY st.transactionDate DESC
    `, [startDate, endDate]);

    const totalStockIn = stockIn.reduce((sum, t) => sum + t.quantityMoved, 0);
    const totalStockOut = stockOut.reduce((sum, t) => sum + t.quantityMoved, 0);
    const totalAvailable = availableStock.reduce((sum, p) => sum + p.quantityInStock, 0);

    res.json({
      period,
      dateRange: { startDate, endDate },
      summary: {
        totalAvailableStock: totalAvailable,
        totalStockIn,
        totalStockOut,
      },
      availableStock,
      stockIn,
      stockOut,
    });
  } catch (error) {
    res.status(500).json({ message: 'Failed to generate report.', error: error.message });
  }
});

module.exports = router;
