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

const router = express.Router();
router.use(authMiddleware);

router.get('/daily', async (req, res) => {
  try {
    const { date } = req.query;
    if (!date) {
      return res.status(400).json({ message: 'Date parameter is required (YYYY-MM-DD).' });
    }

    const [sales] = await pool.query(`
      SELECT s.sale_id, s.quantity, s.unit_price, s.total_price, s.sale_date,
             c.fullname AS customer_name, p.product_name
      FROM sales s
      JOIN customers c ON s.customer_id = c.customer_id
      JOIN products p ON s.product_id = p.product_id
      WHERE DATE(s.sale_date) = ?
      ORDER BY s.sale_date DESC
    `, [date]);

    const totalRevenue = sales.reduce((sum, s) => sum + parseFloat(s.total_price), 0);
    const totalItems = sales.reduce((sum, s) => sum + s.quantity, 0);

    res.json({ date, sales, summary: { totalSales: sales.length, totalItems, totalRevenue } });
  } catch (error) {
    console.error('Daily report error:', error);
    res.status(500).json({ message: 'Failed to generate daily report.' });
  }
});

router.get('/monthly', async (req, res) => {
  try {
    const { startDate, endDate } = req.query;
    if (!startDate || !endDate) {
      return res.status(400).json({ message: 'startDate and endDate are required (YYYY-MM-DD).' });
    }

    const [sales] = await pool.query(`
      SELECT s.sale_id, s.quantity, s.unit_price, s.total_price, s.sale_date,
             c.fullname AS customer_name, p.product_name
      FROM sales s
      JOIN customers c ON s.customer_id = c.customer_id
      JOIN products p ON s.product_id = p.product_id
      WHERE DATE(s.sale_date) BETWEEN ? AND ?
      ORDER BY s.sale_date DESC
    `, [startDate, endDate]);

    const totalRevenue = sales.reduce((sum, s) => sum + parseFloat(s.total_price), 0);
    const totalItems = sales.reduce((sum, s) => sum + s.quantity, 0);

    res.json({ startDate, endDate, sales, summary: { totalSales: sales.length, totalItems, totalRevenue } });
  } catch (error) {
    console.error('Monthly report error:', error);
    res.status(500).json({ message: 'Failed to generate monthly report.' });
  }
});

router.get('/stock', async (req, res) => {
  try {
    const [products] = await pool.query(`
      SELECT p.product_id, p.product_name, p.category, p.quantity AS available_stock,
             p.price, COALESCE(SUM(s.quantity), 0) AS sold_stock
      FROM products p
      LEFT JOIN sales s ON p.product_id = s.product_id
      GROUP BY p.product_id, p.product_name, p.category, p.quantity, p.price
      ORDER BY p.product_name
    `);
    res.json(products);
  } catch (error) {
    console.error('Stock report error:', error);
    res.status(500).json({ message: 'Failed to generate stock report.' });
  }
});

router.get('/customer-purchases', async (req, res) => {
  try {
    const { customerId } = req.query;
    if (!customerId) {
      return res.status(400).json({ message: 'customerId parameter is required.' });
    }

    const [customer] = await pool.query('SELECT * FROM customers WHERE customer_id = ?', [customerId]);
    if (customer.length === 0) {
      return res.status(404).json({ message: 'Customer not found.' });
    }

    const [purchases] = await pool.query(`
      SELECT s.sale_id, s.quantity, s.unit_price, s.total_price, s.sale_date,
             p.product_name, p.category
      FROM sales s
      JOIN products p ON s.product_id = p.product_id
      WHERE s.customer_id = ?
      ORDER BY s.sale_date DESC
    `, [customerId]);

    const totalSpent = purchases.reduce((sum, p) => sum + parseFloat(p.total_price), 0);

    res.json({
      customer: customer[0],
      purchases,
      summary: { totalPurchases: purchases.length, totalSpent },
    });
  } catch (error) {
    console.error('Customer purchase report error:', error);
    res.status(500).json({ message: 'Failed to generate customer purchase report.' });
  }
});

module.exports = router;
