const { Route, Schedule, Vehicle } = require('../models');
const { Op } = require('sequelize');

class RouteController {
  async getAll(req, res, next) {
    try {
      const routes = await Route.findAll({
        where: { is_active: true },
        order: [['origin', 'ASC']],
      });
      res.json({ routes });
    } catch (error) {
      next(error);
    }
  }

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

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

  async getSchedulesForRoute(req, res, next) {
    try {
      const schedules = await Schedule.findAll({
        where: { route_id: req.params.id, is_active: true },
        include: [{ model: Vehicle }],
        order: [['departure_day', 'ASC'], ['departure_time', 'ASC']],
      });
      res.json({ schedules });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new RouteController();
