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

router.get('/', ensureAuth, async (req, res) => {
  try {
    const trips = await Trip.find().sort({ tripDate: -1 }).populate('vehicle', 'vehicleName plateNumber model');
    res.json(trips);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

router.post('/', ensureAuth, async (req, res) => {
  try {
    const { vehicle, tripDate, destination, fuelConsumed, tripCost } = req.body;
    if (!vehicle || !tripDate || !destination || fuelConsumed === undefined || tripCost === undefined) {
      return res.status(400).json({ message: 'All trip fields are required' });
    }

    const vehicleExists = await Vehicle.findById(vehicle);
    if (!vehicleExists) {
      return res.status(404).json({ message: 'Selected vehicle does not exist' });
    }

    const trip = await Trip.create({ vehicle, tripDate, destination, fuelConsumed, tripCost });
    res.status(201).json(trip);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

module.exports = router;
