"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RopidGTFSStopTimesModel = void 0;
const const_1 = require("../../schema-definitions/const");
const ropid_gtfs_1 = require("../../schema-definitions/ropid-gtfs");
const StopTimesDto_1 = require("../../schema-definitions/ropid-gtfs/models/StopTimesDto");
const integration_engine_1 = require("@golemio/core/dist/integration-engine");
const connectors_1 = require("@golemio/core/dist/integration-engine/connectors");
const golemio_errors_1 = require("@golemio/core/dist/shared/golemio-errors");
const golemio_validator_1 = require("@golemio/core/dist/shared/golemio-validator");
const sequelize_1 = __importDefault(require("@golemio/core/dist/shared/sequelize"));
class RopidGTFSStopTimesModel extends integration_engine_1.PostgresModel {
    constructor() {
        super(ropid_gtfs_1.RopidGTFS.stop_times.name + "Model", {
            outputSequelizeAttributes: ropid_gtfs_1.RopidGTFS.stop_times.outputSequelizeAttributes,
            pgTableName: ropid_gtfs_1.RopidGTFS.stop_times.pgTableName,
            pgSchema: const_1.PG_SCHEMA,
            savingType: "insertOnly",
        }, new golemio_validator_1.JSONSchemaValidator(ropid_gtfs_1.RopidGTFS.stop_times.name + "ModelValidator", StopTimesDto_1.StopTimesDto.jsonSchema));
        this.findTripStops = async (tripIds) => {
            const connection = connectors_1.PostgresConnector.getConnection();
            try {
                return await connection.query(`
                    SELECT t1.trip_id, array_to_json(array_agg(
                        json_build_object('stop_id', t1.stop_id, 'stop_sequence', t1.stop_sequence, 'cis', t2.cis)
                            ORDER BY t1.stop_sequence
                    )) as trip_stops
                    FROM ${const_1.PG_SCHEMA}."${this.tableName}" t1
                    LEFT JOIN ${const_1.PG_SCHEMA}."${ropid_gtfs_1.RopidGTFS.cis_stops.pgTableName}" t2
                        on t1.stop_id = CONCAT('U',REPLACE(id,'/','Z'))
                    WHERE t1.trip_id in (${tripIds.map((tripId) => "'" + tripId + "'").join(",")})
                    GROUP BY t1.trip_id
                `, { type: sequelize_1.default.QueryTypes.SELECT, raw: true });
            }
            catch (err) {
                throw new golemio_errors_1.GeneralError("Cannot find trip stops", this.name, err);
            }
        };
    }
}
exports.RopidGTFSStopTimesModel = RopidGTFSStopTimesModel;
//# sourceMappingURL=RopidGTFSStopTimesModel.js.map