"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); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PresetLogRepository = void 0;
const ModuleContainerToken_1 = require("../../../../ioc/ModuleContainerToken");
const DeparturePresetsRepository_1 = require("../../../data-access/DeparturePresetsRepository");
const const_1 = require("../../../../../schema-definitions/const");
const models_1 = require("../../../../../schema-definitions/ropid-departures-preset-logs/models");
const ropid_departures_presets_1 = require("../../../../../schema-definitions/ropid-departures-presets");
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 PresetLogRepository = class PresetLogRepository extends models_2.PostgresModel {
    constructor(departurePresetsRepository) {
        super("PresetLogPepository", {
            pgTableName: models_1.PresetLogModel.tableName,
            pgSchema: const_1.PG_SCHEMA,
            outputSequelizeAttributes: models_1.PresetLogModel.attributeModel,
            savingType: "insertOrUpdate",
        }, new golemio_validator_1.JSONSchemaValidator("PresetLogPepository", models_1.PresetLogModel.arrayJsonSchema));
        this.findUnprocessed = async () => {
            try {
                return await this.sequelizeModel.findAll({
                    attributes: ["id", "device_alias", "received_at"],
                    include: [
                        {
                            association: ropid_departures_presets_1.RopidDeparturesPresets.pgTableName,
                            attributes: [],
                            required: true,
                        },
                    ],
                    where: {
                        is_processed: false,
                        received_at: {
                            [sequelize_1.Op.gte]: sequelize_1.default.literal(`NOW() - INTERVAL '10 MIN'`),
                        },
                    },
                });
            }
            catch (err) {
                throw new golemio_errors_1.GeneralError("Error while fetching unprocessed preset logs", this.constructor.name, err);
            }
        };
        this.saveData = async (data) => {
            try {
                await this.validate(data);
                await this.sequelizeModel.bulkCreate(data, {
                    ignoreDuplicates: true,
                });
            }
            catch (err) {
                throw new golemio_errors_1.GeneralError("Error while creating preset logs", this.constructor.name, err);
            }
        };
        this.markAsProcessed = async (logIds) => {
            try {
                await this.sequelizeModel.update({ is_processed: true }, {
                    where: sequelize_1.default.where(sequelize_1.default.col("id"), {
                        [sequelize_1.Op.in]: logIds,
                    }),
                });
            }
            catch (err) {
                throw new golemio_errors_1.GeneralError("Error while marking preset logs as processed", this.constructor.name, err);
            }
        };
        this.deleteNHoursOldData = async (hours) => {
            try {
                return await this.sequelizeModel.destroy({
                    where: {
                        received_at: {
                            [sequelize_1.Op.lt]: sequelize_1.default.literal(`NOW() - INTERVAL '${hours} HOURS'`),
                        },
                    },
                });
            }
            catch (err) {
                throw new golemio_errors_1.GeneralError("Error while purging preset logs", this.constructor.name, err);
            }
        };
        this.sequelizeModel.hasOne(departurePresetsRepository["sequelizeModel"], {
            as: ropid_departures_presets_1.RopidDeparturesPresets.pgTableName,
            foreignKey: "route_name",
            sourceKey: "device_alias",
            constraints: false,
            scope: {
                is_testing: false,
            },
        });
    }
};
exports.PresetLogRepository = PresetLogRepository;
exports.PresetLogRepository = PresetLogRepository = __decorate([
    (0, tsyringe_1.injectable)(),
    __param(0, (0, tsyringe_1.inject)(ModuleContainerToken_1.ModuleContainerToken.DeparturePresetsRepository)),
    __metadata("design:paramtypes", [DeparturePresetsRepository_1.DeparturePresetsRepository])
], PresetLogRepository);
//# sourceMappingURL=PresetLogRepository.js.map