"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 __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 __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;
    };
})();
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 DescriptorRepository_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DescriptorRepository = void 0;
const RepositoryUtils_1 = require("../../../../shared/RepositoryUtils");
const const_1 = require("../../../../../schema-definitions/const");
const models_1 = require("../../../../../schema-definitions/vehicle-descriptors/models");
const CoreToken_1 = require("@golemio/core/dist/helpers/ioc/CoreToken");
const models_2 = require("@golemio/core/dist/integration-engine/models");
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 tsyringe_1 = require("@golemio/core/dist/shared/tsyringe");
let DescriptorRepository = DescriptorRepository_1 = class DescriptorRepository extends models_2.PostgresModel {
    constructor(logger) {
        super(DescriptorRepository_1.REPOSITORY_NAME, {
            pgTableName: models_1.DescriptorModel.tableName,
            pgSchema: const_1.PG_SCHEMA,
            outputSequelizeAttributes: models_1.DescriptorModel.attributeModel,
            savingType: "insertOrUpdate",
        }, new golemio_validator_1.JSONSchemaValidator(DescriptorRepository_1.REPOSITORY_NAME + "Validator", models_1.DescriptorModel.arrayJsonSchema));
        this.logger = logger;
        this.deleteNHoursOldData = async (hours) => {
            try {
                return await this.sequelizeModel.destroy({
                    where: {
                        updated_at: {
                            [sequelize_1.Op.lt]: sequelize_1.default.literal(`NOW() - INTERVAL '${hours} HOURS'`),
                        },
                    },
                });
            }
            catch (err) {
                throw new golemio_errors_1.GeneralError("Error while purging old data", this.constructor.name, err);
            }
        };
    }
    async findAccessDescByRegistrationNumbers(registrationNumbers, gtfsRouteType) {
        try {
            return await this.sequelizeModel.findAll({
                attributes: ["is_wheelchair_accessible", "registration_number"],
                where: {
                    registration_number: registrationNumbers,
                    gtfs_route_type: gtfsRouteType,
                },
            });
        }
        catch (err) {
            throw new golemio_errors_1.GeneralError("findAccessDescByRegistrationNumbers: failed to get descriptors", this.name, err);
        }
    }
    async refreshData(descriptors) {
        let transaction;
        try {
            await this.validate(descriptors);
            transaction = await this.sequelizeModel.sequelize?.transaction();
            await this.sequelizeModel.destroy({ where: {}, transaction });
            await this.sequelizeModel.bulkCreate(descriptors, {
                ignoreDuplicates: true,
                returning: false,
                transaction,
            });
            await transaction?.commit();
        }
        catch (err) {
            await transaction?.rollback();
            RepositoryUtils_1.RepositoryUtils.mapSequelizeError(err, this.constructor.name, "refreshData");
        }
    }
};
exports.DescriptorRepository = DescriptorRepository;
DescriptorRepository.REPOSITORY_NAME = "VPDescriptorRepository";
exports.DescriptorRepository = DescriptorRepository = DescriptorRepository_1 = __decorate([
    (0, tsyringe_1.injectable)(),
    __param(0, (0, tsyringe_1.inject)(CoreToken_1.CoreToken.Logger)),
    __metadata("design:paramtypes", [Object])
], DescriptorRepository);
//# sourceMappingURL=DescriptorRepository.js.map