const { Vehicle, Schedule, Driver } = require('../models');

class VehicleController {
  async getAll(req, res, next) {
    try {
      const vehicles = await Vehicle.findAll({
        where: { is_active: true },
        order: [['vehicle_name', 'ASC']],
      });
      res.json({ vehicles });
    } catch (error) {
      next(error);
    }
  }

  async getById(req, res, next) {
    try {
      const vehicle = await Vehicle.findByPk(req.params.id, {
        include: [{ model: Schedule }, { model: Driver }],
      });
      if (!vehicle) {
        return res.status(404).json({ error: 'Vehicle not found' });
      }
      res.json({ vehicle });
    } catch (error) {
      next(error);
    }
  }

  async create(req, res, next) {
    try {
      const vehicle = await Vehicle.create(req.body);
      res.status(201).json({ vehicle });
    } catch (error) {
      next(error);
    }
  }

  async update(req, res, next) {
    try {
      const vehicle = await Vehicle.findByPk(req.params.id);
      if (!vehicle) {
        return res.status(404).json({ error: 'Vehicle not found' });
      }
      await vehicle.update(req.body);
      res.json({ vehicle });
    } catch (error) {
      next(error);
    }
  }

  async remove(req, res, next) {
    try {
      const vehicle = await Vehicle.findByPk(req.params.id);
      if (!vehicle) {
        return res.status(404).json({ error: 'Vehicle not found' });
      }
      vehicle.is_active = false;
      await vehicle.save();
      res.json({ message: 'Vehicle deactivated' });
    } catch (error) {
      next(error);
    }
  }

  async getTypes(req, res, next) {
    try {
      const types = await Vehicle.aggregate('vehicle_type', 'DISTINCT', { plain: false });
      res.json({ types: types.map((t) => t.DISTINCT) });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new VehicleController();
