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

router.get('/', auth, async (req, res) => {
  try {
    const logs = await FuelLog.find().sort({ fuel_date: -1 })
      .populate('vehicle_id', 'vehicle_number model')
      .populate('driver_id', 'name');
    res.json(logs);
  } catch (err) { res.status(500).json({ message: err.message }); }
});

router.get('/stats', auth, async (req, res) => {
  try {
    const agg = await FuelLog.aggregate([{
      $group: { _id: null, total_records: { $sum: 1 }, total_liters: { $sum: '$liters' }, total_cost: { $sum: '$total_cost' }, avg_liters: { $avg: '$liters' } }
    }]);
    res.json(agg[0] || { total_records: 0, total_liters: 0, total_cost: 0, avg_liters: 0 });
  } catch (err) { res.status(500).json({ message: err.message }); }
});

router.post('/', auth, async (req, res) => {
  try {
    const log = await FuelLog.create(req.body);
    await Vehicle.findByIdAndUpdate(req.body.vehicle_id, { mileage: req.body.odometer_reading });
    res.status(201).json(log);
  } catch (err) { res.status(500).json({ message: err.message }); }
});

router.put('/:id', auth, async (req, res) => {
  try {
    const log = await FuelLog.findByIdAndUpdate(req.params.id, req.body, { new: true });
    res.json(log);
  } catch (err) { res.status(500).json({ message: err.message }); }
});

router.delete('/:id', auth, async (req, res) => {
  try {
    await FuelLog.findByIdAndDelete(req.params.id);
    res.json({ message: 'Deleted successfully' });
  } catch (err) { res.status(500).json({ message: err.message }); }
});

module.exports = router;
