const router = require('express').Router();
const Vehicle = require('../models/Vehicle');
const Driver = require('../models/Driver');
const Trip = require('../models/Trip');
const FuelLog = require('../models/FuelLog');
const Invoice = require('../models/Invoice');
const Maintenance = require('../models/Maintenance');
const { auth } = require('../middleware/auth');

router.get('/', auth, async (req, res) => {
  try {
    const [totalV, availableV, onTripV, maintV] = await Promise.all([
      Vehicle.countDocuments(), Vehicle.countDocuments({ status: 'available' }),
      Vehicle.countDocuments({ status: 'on_trip' }), Vehicle.countDocuments({ status: 'maintenance' })
    ]);
    const [totalD, activeD] = await Promise.all([Driver.countDocuments(), Driver.countDocuments({ employment_status: 'active' })]);
    const [totalT, activeT, completedT] = await Promise.all([
      Trip.countDocuments(), Trip.countDocuments({ status: 'in_progress' }), Trip.countDocuments({ status: 'completed' })
    ]);
    const fuelAgg = await FuelLog.aggregate([{ $group: { _id: null, total_cost: { $sum: '$total_cost' }, total_liters: { $sum: '$liters' } } }]);
    const revAgg = await Invoice.aggregate([{
      $group: { _id: null, total: { $sum: '$total_amount' }, paid: { $sum: { $cond: [{ $eq: ['$status','paid'] }, '$total_amount', 0] } } }
    }]);
    const [totalM, upcomingM] = await Promise.all([Maintenance.countDocuments(), Maintenance.countDocuments({ status: 'scheduled' })]);
    const recentTrips = await Trip.find().sort({ createdAt: -1 }).limit(5)
      .populate('driver_id', 'name').populate('vehicle_id', 'vehicle_number');
    const fuelByMonth = await FuelLog.aggregate([{
      $group: { _id: { $dateToString: { format: '%Y-%m', date: '$fuel_date' } }, cost: { $sum: '$total_cost' }, liters: { $sum: '$liters' } }
    }, { $sort: { _id: -1 } }, { $limit: 6 }]);

    res.json({
      vehicles: { total: totalV, available: availableV, on_trip: onTripV, in_maintenance: maintV },
      drivers: { total: totalD, active: activeD },
      trips: { total: totalT, active: activeT, completed: completedT },
      fuel: fuelAgg[0] || { total_cost: 0, total_liters: 0 },
      revenue: revAgg[0] || { total: 0, paid: 0 },
      maintenance: { total: totalM, upcoming: upcomingM },
      recentTrips,
      fuelByMonth: fuelByMonth.map(x => ({ month: x._id, cost: x.cost, liters: x.liters }))
    });
  } catch (err) { res.status(500).json({ message: err.message }); }
});

module.exports = router;
