"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var JISEventsRepository_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.JISEventsRepository = void 0;
const const_1 = require("../../../schema-definitions/const");
const JISEventsModel_1 = require("../../../schema-definitions/jis/models/JISEventsModel");
const AbstractValidatableRepository_1 = require("@golemio/core/dist/helpers/data-access/postgres/repositories/AbstractValidatableRepository");
const CoreToken_1 = require("@golemio/core/dist/helpers/ioc/CoreToken");
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 = require("@golemio/core/dist/shared/sequelize");
const tsyringe_1 = require("@golemio/core/dist/shared/tsyringe");
const JISContainerToken_1 = require("../ioc/JISContainerToken");
const JISEventsRopidGTFSRoutesRepository_1 = require("./JISEventsRopidGTFSRoutesRepository");
const Di_1 = require("../../ropid-gtfs/ioc/Di");
const RopidGtfsContainerToken_1 = require("../../ropid-gtfs/ioc/RopidGtfsContainerToken");
const RepositoryUtils_1 = require("../../shared/RepositoryUtils");
const JISEventEffectHelper_1 = require("../../../helpers/jis/JISEventEffectHelper");
let JISEventsRepository = JISEventsRepository_1 = class JISEventsRepository extends AbstractValidatableRepository_1.AbstractValidatableRepository {
    constructor(connector, logger, eventsRopidGTFSRoutesRepository) {
        super(connector, logger);
        this.logger = logger;
        this.eventsRopidGTFSRoutesRepository = eventsRopidGTFSRoutesRepository;
        this.schema = const_1.PG_SCHEMA;
        this.tableName = JISEventsModel_1.JISEventsModel.tableName;
        this.validator = new golemio_validator_1.JSONSchemaValidator("JISEventsRepository", JISEventsModel_1.JISEventsModel.jsonSchema);
        this.sequelizeModel = connector.getConnection().define(this.tableName, JISEventsModel_1.JISEventsModel.attributeModel, {
            schema: this.schema,
            hooks: JISEventsRepository_1.hooks,
        });
        this.ropidGTFSRoutesRepository = Di_1.RopidGtfsContainer.resolve(RopidGtfsContainerToken_1.RopidGtfsContainerToken.RopidGTFSRoutesRepository);
        this.sequelizeModel.belongsToMany(this.ropidGTFSRoutesRepository["sequelizeModel"], {
            through: this.eventsRopidGTFSRoutesRepository["sequelizeModel"],
            foreignKey: "event_id",
            otherKey: "route_id",
            as: "routes",
        });
    }
    async getCurrentIncidents(organizationNames) {
        const now = new Date();
        try {
            return (await this.sequelizeModel.findAll({
                where: {
                    type: "INCIDENT",
                    organization_name: organizationNames,
                    deleted_timestamp: { [sequelize_1.Op.is]: null },
                    [sequelize_1.Op.or]: [{ active_period_end: null }, { active_period_end: { [sequelize_1.Op.gte]: now } }],
                },
                include: [
                    {
                        model: this.ropidGTFSRoutesRepository["sequelizeModel"],
                        as: "routes",
                        attributes: ["route_id"],
                        required: true,
                    },
                ],
            }));
        }
        catch (err) {
            throw new golemio_errors_1.GeneralError("Error in getCurrentIncidents", this.constructor.name, err);
        }
    }
    /**
     * Refresh all data from VYMI
     *
     * @param data The data to be upserted
     * @param options Options for the operation
     */
    async upsertAll(data, options) {
        try {
            // single-event update – race condition protection
            if (data.length === 1) {
                const incoming = data[0];
                const existing = await this.sequelizeModel.findByPk(incoming.id, {
                    transaction: options?.transaction,
                });
                const incomingDeleted = incoming.deleted_timestamp ? new Date(incoming.deleted_timestamp).getTime() : null;
                const existingDeleted = existing?.deleted_timestamp ? new Date(existing.deleted_timestamp).getTime() : null;
                if (!existing ||
                    new Date(incoming.updated_timestamp).getTime() > new Date(existing.updated_timestamp).getTime() ||
                    incomingDeleted !== existingDeleted) {
                    const [record, created] = await this.sequelizeModel.upsert(incoming, {
                        transaction: options?.transaction,
                    });
                    this.logger.info(`${this.constructor.name}.upsertAll: ${created ? "inserted" : "updated"} single JIS event ID=${incoming.id}`);
                    return [record];
                }
                else {
                    this.logger.info(`${this.constructor.name}.upsertAll: skipped outdated single JIS event ID=${incoming.id}`);
                    return [];
                }
            }
            const upserted = await this.sequelizeModel.bulkCreate(data, {
                updateOnDuplicate: this.getUpdateAttributes(),
                transaction: options?.transaction,
            });
            this.logger.info(`${this.constructor.name}.upsertAll: upserted ${upserted.length} JIS events.`);
            return upserted;
        }
        catch (err) {
            RepositoryUtils_1.RepositoryUtils.mapSequelizeError(err, this.constructor.name, "upsertAll");
        }
    }
    getUpdateAttributes() {
        return Object.keys(JISEventsModel_1.JISEventsModel.attributeModel).filter((attribute) => !["created_at"].includes(attribute));
    }
};
exports.JISEventsRepository = JISEventsRepository;
JISEventsRepository.hooks = {
    beforeBulkCreate(events) {
        events.forEach((event) => {
            event.effect = JISEventEffectHelper_1.JISEventEffectHelper.getEffectAsString(event.effect);
        });
    },
    beforeValidate(event) {
        // to pass sequelize validation of being a string type
        event.effect = JISEventEffectHelper_1.JISEventEffectHelper.getEffectAsString(event.effect);
    },
    beforeUpsert(event) {
        event.effect = JISEventEffectHelper_1.JISEventEffectHelper.getEffectAsString(event.effect);
    },
    afterBulkCreate(events) {
        events.forEach((event) => {
            event.effect = JISEventEffectHelper_1.JISEventEffectHelper.getEffectAsList(event.effect);
        });
    },
};
exports.JISEventsRepository = JISEventsRepository = JISEventsRepository_1 = __decorate([
    (0, tsyringe_1.injectable)(),
    __param(0, (0, tsyringe_1.inject)(CoreToken_1.CoreToken.PostgresConnector)),
    __param(1, (0, tsyringe_1.inject)(CoreToken_1.CoreToken.Logger)),
    __param(2, (0, tsyringe_1.inject)(JISContainerToken_1.JISContainerToken.JISEventsRopidGTFSRoutesRepository)),
    __metadata("design:paramtypes", [Object, Object, JISEventsRopidGTFSRoutesRepository_1.JISEventsRopidGTFSRoutesRepository])
], JISEventsRepository);
//# sourceMappingURL=JISEventsRepository.js.map