"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 JISInfotextsRedisRepository_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.JISInfotextsRedisRepository = void 0;
const const_1 = require("../../../schema-definitions/jis/redis/const");
const JISInfotextDtoSchema_1 = require("../../../schema-definitions/jis/redis/schemas/JISInfotextDtoSchema");
const integration_engine_1 = require("@golemio/core/dist/integration-engine");
const golemio_errors_1 = require("@golemio/core/dist/shared/golemio-errors");
const golemio_validator_1 = require("@golemio/core/dist/shared/golemio-validator");
const tsyringe_1 = require("@golemio/core/dist/shared/tsyringe");
const node_crypto_1 = require("node:crypto");
const TTL_SECONDS_BEFORE_DELETE = 60;
let JISInfotextsRedisRepository = JISInfotextsRedisRepository_1 = class JISInfotextsRedisRepository extends integration_engine_1.RedisModel {
    constructor() {
        super("JISInfotextsRedisRepository", {
            isKeyConstructedFromData: false,
            prefix: JISInfotextsRedisRepository_1.NAMESPACE_PREFIX,
        }, new golemio_validator_1.JSONSchemaValidator("JISInfotextsRedisRepositoryValidator", JISInfotextDtoSchema_1.JISInfotextDtoSchema));
    }
    async refreshData(infotexts) {
        try {
            const oldSetName = (await this.connection.get(`${this.prefix}:activeSetName`)) ?? "";
            await this.createNewCache(infotexts);
            await this.deleteOldCache(oldSetName);
        }
        catch (err) {
            throw new golemio_errors_1.GeneralError("refreshData failed", this.constructor.name, err);
        }
    }
    async createNewCache(infotexts) {
        try {
            await this.validator.Validate(infotexts);
        }
        catch (error) {
            throw new golemio_errors_1.GeneralError(`JISInfotextsRedisRepository: data validation failed: ${error.message}`, this.constructor.name, error);
        }
        try {
            const infotextIdsByStopId = new Map();
            const infotextsByInfotextId = new Map();
            for (const infotext of infotexts) {
                infotextsByInfotextId.set(infotext.id, JSON.stringify(infotext));
                for (const { stop_id } of infotext?.stops ?? []) {
                    let stopInfotextsIds = infotextIdsByStopId.get(stop_id) ?? [];
                    stopInfotextsIds.push(infotext.id);
                    infotextIdsByStopId.set(stop_id, stopInfotextsIds);
                }
            }
            const setName = (0, node_crypto_1.randomBytes)(4).toString("hex");
            const pipeline = this.connection.pipeline();
            pipeline.hset(`${this.prefix}:${setName}:infotexts`, infotextsByInfotextId);
            pipeline.hset(`${this.prefix}:${setName}:stops-infotexts`, infotextIdsByStopId);
            pipeline.publish(`${this.prefix}`, `${this.prefix}:${setName}`);
            pipeline.set(`${this.prefix}:activeSetName`, `${this.prefix}:${setName}`);
            await pipeline.exec();
        }
        catch (err) {
            throw new golemio_errors_1.GeneralError("createNewCache failed", this.constructor.name, err);
        }
    }
    async deleteOldCache(setName) {
        try {
            const pipeline = this.connection.pipeline();
            pipeline.expire(`${setName}:infotexts`, TTL_SECONDS_BEFORE_DELETE);
            pipeline.expire(`${setName}:stops-infotexts`, TTL_SECONDS_BEFORE_DELETE);
            await pipeline.exec();
        }
        catch (err) {
            throw new golemio_errors_1.GeneralError("deleteOldCache failed", this.constructor.name, err);
        }
    }
};
exports.JISInfotextsRedisRepository = JISInfotextsRedisRepository;
JISInfotextsRedisRepository.NAMESPACE_PREFIX = const_1.JIS_NAMESPACE_PREFIX;
exports.JISInfotextsRedisRepository = JISInfotextsRedisRepository = JISInfotextsRedisRepository_1 = __decorate([
    (0, tsyringe_1.injectable)(),
    __metadata("design:paramtypes", [])
], JISInfotextsRedisRepository);
//# sourceMappingURL=JISInfotextsRedisRepository.js.map