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

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

router.get('/summary', async (req, res) => {
  try {
    const [[{ totalProducts }]] = await pool.query('SELECT COUNT(*) AS totalProducts FROM products');
    const [[{ totalCustomers }]] = await pool.query('SELECT COUNT(*) AS totalCustomers FROM customers');
    const [[{ totalSales }]] = await pool.query('SELECT COUNT(*) AS totalSales FROM sales');
    const [[{ totalRevenue }]] = await pool.query('SELECT COALESCE(SUM(total_price), 0) AS totalRevenue FROM sales');

    const [recentSales] = await pool.query(`
      SELECT s.sale_id, 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
      ORDER BY s.sale_date DESC LIMIT 5
    `);

    const [lowStock] = await pool.query(
      'SELECT product_id, product_name, quantity FROM products WHERE quantity <= 5 ORDER BY quantity ASC LIMIT 5'
    );

    res.json({
      totalProducts,
      totalCustomers,
      totalSales,
      totalRevenue: parseFloat(totalRevenue),
      recentSales,
      lowStock,
    });
  } catch (error) {
    console.error('Dashboard summary error:', error);
    res.status(500).json({ message: 'Failed to fetch dashboard summary.' });
  }
});

module.exports = router;
