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

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

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

router.post('/', auth, async (req, res) => {
  try {
    const m = await Maintenance.create(req.body);
    if (req.body.status === 'in_progress') await Vehicle.findByIdAndUpdate(req.body.vehicle_id, { status: 'maintenance' });
    if (req.body.status === 'completed') await Vehicle.findByIdAndUpdate(req.body.vehicle_id, { status: 'available' });
    res.status(201).json(m);
  } catch (err) { res.status(500).json({ message: err.message }); }
});

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

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

module.exports = router;
