"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommonRunsRepository = void 0;
const precomputed_1 = require("../../../../ropid-gtfs/data-access/precomputed");
const const_1 = require("../../../../../schema-definitions/const");
const models_1 = require("../../../../../schema-definitions/vehicle-positions/models");
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 = __importStar(require("@golemio/core/dist/shared/sequelize"));
const AbstractRunRepository_1 = require("./AbstractRunRepository");
const CommonRunsMessagesRepository_1 = require("./CommonRunsMessagesRepository");
class CommonRunsRepository extends AbstractRunRepository_1.AbstractRunRepository {
    constructor() {
        super("CommonRunsRepository", {
            pgTableName: models_1.CommonRunsModel.TABLE_NAME,
            pgSchema: const_1.PG_SCHEMA,
            outputSequelizeAttributes: models_1.CommonRunsModel.attributeModel,
            savingType: "insertOnly",
            sequelizeAdditionalSettings: {
                indexes: [
                    {
                        fields: ["id"],
                        name: "vehiclepositions_runs_pkey",
                    },
                    {
                        fields: ["route_id", "run_number", "registration_number", "msg_start_timestamp"],
                        name: "vehiclepositions_runs_idx",
                    },
                ],
            },
        }, new golemio_validator_1.JSONSchemaValidator("CommonRunsRepositoryValidator", models_1.CommonRunsModel.jsonSchema));
        this.getRunRecordForUpdate = (run) => {
            return this.sequelizeModel.findOne({
                where: {
                    [sequelize_1.default.Op.or]: [
                        {
                            id: run.id,
                        },
                        {
                            route_id: run.route_id,
                            run_number: run.run_number,
                            registration_number: run.registration_number,
                            msg_last_timestamp: {
                                [sequelize_1.Op.gt]: sequelize_1.default.literal("NOW() - INTERVAL '3 HOURS'"),
                            },
                        },
                    ],
                },
                order: [["msg_last_timestamp", "DESC"]],
                raw: true,
            });
        };
        this.createAndAssociate = async ({ run, run_message }) => {
            const connection = connectors_1.PostgresConnector.getConnection();
            const t = await connection.transaction();
            try {
                const [runRecord] = await this.sequelizeModel.findOrCreate({
                    where: { id: run.id },
                    defaults: { ...run },
                    transaction: t,
                });
                const runMessageRecord = await this.runsMessagesRepository["sequelizeModel"].create({ ...run_message, runs_id: run.id }, { transaction: t });
                await t.commit();
                return {
                    run: runRecord.get({ plain: true }),
                    run_message: runMessageRecord.get({ plain: true }),
                };
            }
            catch (err) {
                await t.rollback();
                throw new golemio_errors_1.RecoverableError("createAndAssociate: error while saving to database", this.name, err);
            }
        };
        this.updateAndAssociate = async ({ run, run_message }, runId) => {
            try {
                const [[, runRecord], runMessageRecord] = await Promise.all([
                    this.update({ msg_last_timestamp: run.msg_last_timestamp }, { where: { id: runId }, returning: true, plain: true }),
                    this.runsMessagesRepository["sequelizeModel"].create({ ...run_message, runs_id: runId }),
                ]);
                return {
                    run: runRecord.get({ plain: true }),
                    run_message: runMessageRecord.get({ plain: true }),
                };
            }
            catch (err) {
                throw new golemio_errors_1.RecoverableError("updateAndAssociate: error while saving to database", this.name, err);
            }
        };
        this.getScheduledTrips = (origin_route_name, run_number, msg_last_timestamp) => {
            return this.tripScheduleRepository.findAll({
                attributes: {
                    include: [
                        [sequelize_1.default.cast(sequelize_1.default.col("start_timestamp"), "varchar"), "start_timestamp"],
                        [sequelize_1.default.cast(sequelize_1.default.col("end_timestamp"), "varchar"), "end_timestamp"],
                    ],
                    exclude: ["start_timestamp", "end_timestamp"],
                },
                where: {
                    origin_route_name,
                    run_number,
                    [sequelize_1.default.Op.or]: [
                        sequelize_1.default.literal(`date = '${msg_last_timestamp}'::DATE`),
                        sequelize_1.default.literal(`date = ('${msg_last_timestamp}'::TIMESTAMP - INTERVAL '1 day')::DATE`),
                        sequelize_1.default.literal(`date = ('${msg_last_timestamp}'::TIMESTAMP + INTERVAL '1 day')::DATE`),
                    ],
                },
                order: [
                    ["date", "ASC"],
                    ["min_stop_time", "ASC"],
                ],
            });
        };
        this.runsMessagesRepository = new CommonRunsMessagesRepository_1.CommonRunsMessagesRepository();
        this.runsMessagesRepository["sequelizeModel"].belongsTo(this.sequelizeModel, {
            foreignKey: "runs_id",
            onDelete: "CASCADE",
        });
        this.sequelizeModel.hasMany(this.runsMessagesRepository["sequelizeModel"], {
            sourceKey: "id",
            foreignKey: "runs_id",
            as: "run_messages",
        });
        this.tripScheduleRepository = new precomputed_1.TripScheduleRepository();
    }
}
exports.CommonRunsRepository = CommonRunsRepository;
//# sourceMappingURL=CommonRunsRepository.js.map