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

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

router.get('/stats', auth, async (req, res) => {
  try {
    const total = await Driver.countDocuments();
    const active = await Driver.countDocuments({ employment_status: 'active' });
    const suspended = await Driver.countDocuments({ employment_status: 'suspended' });
    const on_leave = await Driver.countDocuments({ employment_status: 'on_leave' });
    res.json({ total, active, suspended, on_leave });
  } catch (err) { res.status(500).json({ message: err.message }); }
});

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

router.post('/', auth, async (req, res) => {
  try {
    const d = await Driver.create(req.body);
    res.status(201).json(d);
  } catch (err) {
    if (err.code === 11000) return res.status(400).json({ message: 'License number already exists' });
    res.status(500).json({ message: err.message });
  }
});

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

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

module.exports = router;
