const { Stop, RouteStop, Route } = require('../models');

class StopController {
  async getAll(req, res, next) {
    try {
      const stops = await Stop.findAll({ where: { is_active: true }, order: [['name', 'ASC']] });
      res.json({ stops });
    } catch (error) {
      next(error);
    }
  }

  async getByRoute(req, res, next) {
    try {
      const { routeId } = req.params;
      const routeStops = await RouteStop.findAll({
        where: { route_id: routeId },
        include: [{ model: Stop }],
        order: [['order', 'ASC']],
      });
      const stops = routeStops.map((rs) => ({
        id: rs.stop.id,
        name: rs.stop.name,
        country: rs.stop.country,
        is_border: rs.stop.is_border,
        order: rs.order,
        distance_from_previous_km: rs.distance_from_previous_km,
      }));
      res.json({ stops });
    } catch (error) {
      next(error);
    }
  }

  async create(req, res, next) {
    try {
      const { name, country, is_border } = req.body;
      if (!name || !country) return res.status(400).json({ error: 'Name and country required' });
      const stop = await Stop.create({ name, country, is_border: is_border || false });
      res.status(201).json({ stop });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new StopController();
