"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);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.JtiCleanupService = void 0;
const backend_common_1 = require("@n8n/backend-common");
const constants_1 = require("@n8n/constants");
const decorators_1 = require("@n8n/decorators");
const di_1 = require("@n8n/di");
const n8n_core_1 = require("n8n-core");
const token_exchange_jti_repository_1 = require("../database/repositories/token-exchange-jti.repository");
const token_exchange_config_1 = require("../token-exchange.config");
let JtiCleanupService = class JtiCleanupService {
    constructor(logger, config, jtiRepository, instanceSettings) {
        this.config = config;
        this.jtiRepository = jtiRepository;
        this.instanceSettings = instanceSettings;
        this.isShuttingDown = false;
        this.logger = logger.scoped('token-exchange');
    }
    init() {
        if (this.instanceSettings.isLeader)
            this.startCleanup();
    }
    startCleanup() {
        if (this.isShuttingDown || this.cleanupInterval)
            return;
        const intervalMs = this.config.jtiCleanupIntervalSeconds * constants_1.Time.seconds.toMilliseconds;
        this.cleanupInterval = setInterval(async () => await this.cleanup(), intervalMs);
        this.logger.debug(`JTI cleanup scheduled every ${this.config.jtiCleanupIntervalSeconds}s`);
    }
    stopCleanup() {
        clearInterval(this.cleanupInterval);
        this.cleanupInterval = undefined;
    }
    async cleanup() {
        let totalDeleted = 0;
        try {
            let deleted;
            do {
                deleted = await this.jtiRepository.deleteExpiredBatch(this.config.jtiCleanupBatchSize);
                totalDeleted += deleted;
            } while (deleted >= this.config.jtiCleanupBatchSize);
            if (totalDeleted > 0) {
                this.logger.debug('Cleaned up expired JTIs', { count: totalDeleted });
            }
        }
        catch (error) {
            this.logger.error('Failed to clean up expired JTIs', { error });
        }
    }
    shutdown() {
        this.isShuttingDown = true;
        this.stopCleanup();
    }
};
exports.JtiCleanupService = JtiCleanupService;
__decorate([
    (0, decorators_1.OnLeaderTakeover)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], JtiCleanupService.prototype, "startCleanup", null);
__decorate([
    (0, decorators_1.OnLeaderStepdown)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], JtiCleanupService.prototype, "stopCleanup", null);
__decorate([
    (0, decorators_1.OnShutdown)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], JtiCleanupService.prototype, "shutdown", null);
exports.JtiCleanupService = JtiCleanupService = __decorate([
    (0, di_1.Service)(),
    __metadata("design:paramtypes", [backend_common_1.Logger,
        token_exchange_config_1.TokenExchangeConfig,
        token_exchange_jti_repository_1.TokenExchangeJtiRepository,
        n8n_core_1.InstanceSettings])
], JtiCleanupService);
//# sourceMappingURL=jti-cleanup.service.js.map