const router = require('express').Router();
const Trip = require('../models/Trip');
const Vehicle = require('../models/Vehicle');
const Maintenance = require('../models/Maintenance');
const { ensureAuth } = require('../middleware/authMiddleware');

const parseDate = (value) => {
  if (!value) return null;
  const date = new Date(value);
  return Number.isNaN(date.getTime()) ? null : date;
};

const buildDayRange = (date) => {
  const start = new Date(date);
  start.setHours(0, 0, 0, 0);
  const end = new Date(start);
  end.setDate(end.getDate() + 1);
  return { start, end };
};

router.get('/daily-trips', ensureAuth, async (req, res) => {
  try {
    const date = parseDate(req.query.date) || new Date();
    const { start, end } = buildDayRange(date);

    const trips = await Trip.find({ tripDate: { $gte: start, $lt: end } })
      .sort({ tripDate: -1 })
      .populate('vehicle', 'vehicleName');

    res.json(trips.map((trip) => ({
      vehicleName: trip.vehicle?.vehicleName || 'Unknown',
      tripDate: trip.tripDate,
      destination: trip.destination,
      fuelConsumed: trip.fuelConsumed,
      tripCost: trip.tripCost,
    })));
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

router.get('/fleet-status', ensureAuth, async (req, res) => {
  try {
    const date = parseDate(req.query.date) || new Date();
    const { start, end } = buildDayRange(date);

    const [vehicles, tripTotals, maintenanceStatus] = await Promise.all([
      Vehicle.find().sort({ vehicleName: 1 }),
      Trip.aggregate([
        { $match: { tripDate: { $gte: start, $lt: end } } },
        { $group: { _id: '$vehicle', fuelConsumed: { $sum: '$fuelConsumed' } } },
      ]),
      Maintenance.aggregate([
        { $sort: { maintenanceDate: -1 } },
        { $group: { _id: '$vehicle', vehicleStatus: { $first: '$vehicleStatus' } } },
      ]),
    ]);

    const fuelMap = Object.fromEntries(tripTotals.map((item) => [item._id.toString(), item.fuelConsumed]));
    const statusMap = Object.fromEntries(maintenanceStatus.map((item) => [item._id.toString(), item.vehicleStatus]));

    const result = vehicles.map((vehicle) => {
      const status = statusMap[vehicle._id.toString()] || 'Available';
      const availability = ['Under Maintenance', 'Out Of Service'].includes(status) ? 'Not Available' : 'Available';
      return {
        vehicleName: vehicle.vehicleName,
        fuelConsumed: fuelMap[vehicle._id.toString()] || 0,
        maintenanceStatus: status,
        availability,
      };
    });

    res.json(result);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

module.exports = router;
