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

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

router.get('/stats', auth, async (req, res) => {
  try {
    const total = await Trip.countDocuments();
    const scheduled = await Trip.countDocuments({ status: 'scheduled' });
    const in_progress = await Trip.countDocuments({ status: 'in_progress' });
    const completed = await Trip.countDocuments({ status: 'completed' });
    const cancelled = await Trip.countDocuments({ status: 'cancelled' });
    const agg = await Trip.aggregate([{ $group: { _id: null, total_distance: { $sum: '$distance_km' }, total_revenue: { $sum: '$total_cost' } } }]);
    const { total_distance = 0, total_revenue = 0 } = agg[0] || {};
    res.json({ total, scheduled, in_progress, completed, cancelled, total_distance, total_revenue });
  } catch (err) { res.status(500).json({ message: err.message }); }
});

router.get('/:id', auth, async (req, res) => {
  try {
    const t = await Trip.findById(req.params.id)
      .populate('vehicle_id', 'vehicle_number model')
      .populate('driver_id', 'name phone')
      .populate('customer_id', 'name phone');
    if (!t) return res.status(404).json({ message: 'Trip not found' });
    res.json(t);
  } catch (err) { res.status(500).json({ message: err.message }); }
});

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

router.put('/:id', auth, async (req, res) => {
  try {
    const t = await Trip.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (req.body.status === 'completed' || req.body.status === 'cancelled') {
      await Vehicle.findByIdAndUpdate(t.vehicle_id, { status: 'available' });
    }
    res.json(t);
  } catch (err) { res.status(500).json({ message: err.message }); }
});

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

module.exports = router;
