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

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

router.post('/', ensureAuth, async (req, res) => {
  try {
    const { vehicleName, plateNumber, model, fuelType, capacity } = req.body;
    if (!vehicleName || !plateNumber || !model || !fuelType || capacity === undefined) {
      return res.status(400).json({ message: 'All vehicle fields are required' });
    }

    const exists = await Vehicle.findOne({ plateNumber });
    if (exists) {
      return res.status(400).json({ message: 'Vehicle with this plate number already exists' });
    }

    const vehicle = await Vehicle.create({ vehicleName, plateNumber, model, fuelType, capacity });
    res.status(201).json(vehicle);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

module.exports = router;
