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

class SegmentPriceController {
  async getByRoute(req, res, next) {
    try {
      const { routeId } = req.params;
      const { vehicleType } = req.query;

      const where = { route_id: routeId };
      if (vehicleType) where.vehicle_type = vehicleType;

      const prices = await SegmentPrice.findAll({
        where,
        include: [
          { as: 'fromStop', model: Stop, attributes: ['id', 'name', 'country'] },
          { as: 'toStop', model: Stop, attributes: ['id', 'name', 'country'] },
        ],
        order: [['from_stop_id', 'ASC'], ['to_stop_id', 'ASC']],
      });

      res.json({ prices });
    } catch (error) {
      next(error);
    }
  }

  async create(req, res, next) {
    try {
      const { route_id, from_stop_id, to_stop_id, vehicle_type, price_nad, price_bwp } = req.body;
      if (!route_id || !from_stop_id || !to_stop_id || !vehicle_type || !price_nad || !price_bwp) {
        return res.status(400).json({ error: 'All fields required: route_id, from_stop_id, to_stop_id, vehicle_type, price_nad, price_bwp' });
      }

      const [price, created] = await SegmentPrice.findOrCreate({
        where: { route_id, from_stop_id, to_stop_id, vehicle_type },
        defaults: { price_nad, price_bwp },
      });

      if (!created) {
        await price.update({ price_nad, price_bwp });
      }

      res.status(201).json({ price });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new SegmentPriceController();
