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

router.get('/', auth, async (req, res) => {
  try { res.json(await Vehicle.find().sort({ createdAt: -1 })); }
  catch (err) { res.status(500).json({ message: err.message }); }
});

router.get('/stats', auth, async (req, res) => {
  try {
    const total = await Vehicle.countDocuments();
    const available = await Vehicle.countDocuments({ status: 'available' });
    const on_trip = await Vehicle.countDocuments({ status: 'on_trip' });
    const maintenance = await Vehicle.countDocuments({ status: 'maintenance' });
    const inactive = await Vehicle.countDocuments({ status: 'inactive' });
    res.json({ total, available, on_trip, maintenance, inactive });
  } catch (err) { res.status(500).json({ message: err.message }); }
});

router.get('/:id', auth, async (req, res) => {
  try {
    const v = await Vehicle.findById(req.params.id);
    if (!v) return res.status(404).json({ message: 'Vehicle not found' });
    res.json(v);
  } catch (err) { res.status(500).json({ message: err.message }); }
});

router.post('/', auth, async (req, res) => {
  try {
    const v = await Vehicle.create(req.body);
    res.status(201).json(v);
  } catch (err) {
    if (err.code === 11000) return res.status(400).json({ message: 'Duplicate vehicle number or registration' });
    res.status(500).json({ message: err.message });
  }
});

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

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

module.exports = router;
