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

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

router.get('/latest', auth, async (req, res) => {
  try {
    const latest = await GpsTracking.aggregate([
      { $sort: { recorded_at: -1 } },
      { $group: { _id: '$vehicle_id', doc: { $first: '$$ROOT' } } },
      { $replaceRoot: { newRoot: '$doc' } }
    ]);
    const populated = await GpsTracking.populate(latest, { path: 'vehicle_id', select: 'vehicle_number model status' });
    res.json(populated);
  } catch (err) { res.status(500).json({ message: err.message }); }
});

router.post('/', auth, async (req, res) => {
  try {
    const g = await GpsTracking.create(req.body);
    res.status(201).json(g);
  } catch (err) { res.status(500).json({ message: err.message }); }
});

module.exports = router;
