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

class DriverController {
  async getAll(req, res, next) {
    try {
      const drivers = await Driver.findAll({
        include: [{ model: Vehicle }],
        order: [['full_name', 'ASC']],
      });
      res.json({ drivers });
    } catch (error) {
      next(error);
    }
  }

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

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

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

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

module.exports = new DriverController();
