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

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

router.post('/', ensureAuth, async (req, res) => {
  try {
    const { vehicle, serviceType, maintenanceCost, maintenanceDate, vehicleStatus } = req.body;
    if (!vehicle || !serviceType || maintenanceCost === undefined || !maintenanceDate || !vehicleStatus) {
      return res.status(400).json({ message: 'All maintenance fields are required' });
    }

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

    const record = await Maintenance.create({ vehicle, serviceType, maintenanceCost, maintenanceDate, vehicleStatus });
    res.status(201).json(record);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

router.put('/:id', ensureAuth, async (req, res) => {
  try {
    const { vehicle, serviceType, maintenanceCost, maintenanceDate, vehicleStatus } = req.body;
    if (!vehicle || !serviceType || maintenanceCost === undefined || !maintenanceDate || !vehicleStatus) {
      return res.status(400).json({ message: 'All maintenance fields are required' });
    }

    const record = await Maintenance.findByIdAndUpdate(
      req.params.id,
      { vehicle, serviceType, maintenanceCost, maintenanceDate, vehicleStatus },
      { new: true }
    ).populate('vehicle', 'vehicleName plateNumber model');

    if (!record) {
      return res.status(404).json({ message: 'Maintenance record not found' });
    }

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

router.delete('/:id', ensureAuth, async (req, res) => {
  try {
    const record = await Maintenance.findByIdAndDelete(req.params.id);
    if (!record) {
      return res.status(404).json({ message: 'Maintenance record not found' });
    }
    res.json({ message: 'Maintenance record deleted' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

module.exports = router;
