"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "RefreshTokenService", {
    enumerable: true,
    get: function() {
        return RefreshTokenService;
    }
});
const _models = require("../../models");
const _uuid = require("uuid");
const _serverconstants = require("../../server.constants");
const _runtimeexceptions = require("../../exceptions/runtime.exceptions");
const _authorizationconstants = require("../../constants/authorization.constants");
class RefreshTokenService {
    settingsStore;
    logger;
    constructor({ loggerFactory, settingsStore }){
        this.logger = loggerFactory(RefreshTokenService.name);
        this.settingsStore = settingsStore;
    }
    toDto(entity) {
        return {
            id: entity.id,
            userId: entity.userId.toString(),
            expiresAt: entity.expiresAt,
            refreshAttemptsUsed: entity.refreshAttemptsUsed
        };
    }
    async getRefreshToken(refreshToken, throwNotFoundError = true) {
        const userRefreshToken = await _models.RefreshToken.findOne({
            refreshToken
        });
        if (!userRefreshToken) {
            if (throwNotFoundError) {
                throw new _runtimeexceptions.AuthenticationError("The refresh token was not found", _authorizationconstants.AUTH_ERROR_REASON.InvalidOrExpiredRefreshToken);
            }
            return null;
        }
        return userRefreshToken;
    }
    async createRefreshTokenForUserId(userId) {
        const { refreshTokenExpiry } = await this.settingsStore.getCredentialSettings();
        const refreshToken = (0, _uuid.v4)();
        const timespan = refreshTokenExpiry ?? _serverconstants.AppConstants.DEFAULT_REFRESH_TOKEN_EXPIRY;
        if (!refreshTokenExpiry) {
            this.logger.warn(`Refresh token expiry not set in Settings:credentials, using default ${timespan} seconds}`);
        }
        await _models.RefreshToken.create({
            userId,
            expiresAt: Date.now() + timespan * 1000,
            refreshToken,
            refreshAttemptsUsed: 0
        });
        return refreshToken;
    }
    async updateRefreshTokenAttempts(refreshToken, refreshAttemptsUsed) {
        await this.getRefreshToken(refreshToken, true);
        await _models.RefreshToken.updateOne({
            refreshToken
        }, {
            refreshAttemptsUsed
        }, {
            new: true
        });
    }
    async purgeOutdatedRefreshTokensByUserId(userId) {
        const result = await _models.RefreshToken.deleteMany({
            userId,
            expiresAt: {
                $lt: Date.now()
            }
        });
        if (result.deletedCount) {
            this.logger.debug(`Removed ${result.deletedCount} outdated login refresh tokens for user ${userId}`);
        }
    }
    async purgeAllOutdatedRefreshTokens() {
        const result = await _models.RefreshToken.deleteMany({
            expiresAt: {
                $lt: Date.now()
            }
        });
        if (result.deletedCount) {
            this.logger.debug(`Removed ${result.deletedCount} outdated login refresh tokens`);
        }
    }
    async deleteRefreshTokenByUserId(userId) {
        const result = await _models.RefreshToken.deleteMany({
            userId
        });
        if (result.deletedCount) {
            this.logger.debug(`Removed ${result.deletedCount} login refresh tokens`);
        }
    }
    async deleteRefreshToken(refreshToken) {
        const result = await _models.RefreshToken.deleteOne({
            refreshToken
        });
        if (result.deletedCount) {
            this.logger.debug(`Removed ${result.deletedCount} login refresh tokens`);
        }
    }
}

//# sourceMappingURL=refresh-token.service.js.map