"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "RefreshTokenService", {
    enumerable: true,
    get: function() {
        return RefreshTokenService;
    }
});
const _baseservice = require("./base.service");
const _entities = require("../../entities");
const _refreshtokendto = require("../interfaces/refresh-token.dto");
const _runtimeexceptions = require("../../exceptions/runtime.exceptions");
const _uuid = require("uuid");
const _serverconstants = require("../../server.constants");
const _typeorm = require("typeorm");
const _authorizationconstants = require("../../constants/authorization.constants");
class RefreshTokenService extends (0, _baseservice.BaseService)(_entities.RefreshToken, _refreshtokendto.RefreshTokenDto) {
    settingsStore;
    logger;
    constructor({ typeormService, settingsStore, loggerFactory }){
        super({
            typeormService
        });
        this.settingsStore = settingsStore;
        this.logger = loggerFactory(RefreshTokenService.name);
    }
    toDto(entity) {
        return {
            id: entity.id,
            userId: entity.userId,
            expiresAt: entity.expiresAt,
            refreshAttemptsUsed: entity.refreshAttemptsUsed
        };
    }
    async getRefreshToken(refreshToken, throwNotFoundError = true) {
        const entity = await this.repository.findOneBy({
            refreshToken
        });
        if (!entity) {
            if (throwNotFoundError) {
                throw new _runtimeexceptions.AuthenticationError(`The entity ${_entities.RefreshToken.name} by provided refresh token is not found`, _authorizationconstants.AUTH_ERROR_REASON.InvalidOrExpiredRefreshToken);
            }
            return null;
        }
        return entity;
    }
    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 value");
        }
        await this.create({
            userId,
            expiresAt: Date.now() + timespan * 1000,
            refreshToken,
            refreshAttemptsUsed: 0
        });
        return refreshToken;
    }
    async updateRefreshTokenAttempts(refreshToken, refreshAttemptsUsed) {
        await this.getRefreshToken(refreshToken, true);
        await this.repository.update({
            refreshToken
        }, {
            refreshAttemptsUsed
        });
    }
    async purgeAllOutdatedRefreshTokens() {
        const result = await this.repository.delete({
            expiresAt: (0, _typeorm.LessThan)(Date.now())
        });
        if (result.affected) {
            this.logger.debug(`Removed ${result.affected} outdated refresh tokens`);
        }
    }
    async deleteRefreshTokenByUserId(userId) {
        const result = await this.repository.delete({
            userId
        });
        if (result.affected) {
            this.logger.debug(`Removed ${result.affected} login refresh tokens for user`);
        }
    }
    async deleteRefreshToken(refreshToken) {
        const result = await this.repository.delete({
            refreshToken
        });
        if (result.affected) {
            this.logger.debug(`Removed ${result.affected} login refresh tokens`);
        }
    }
    async purgeOutdatedRefreshTokensByUserId(userId) {
        const result = await this.repository.delete({
            userId,
            expiresAt: (0, _typeorm.LessThan)(Date.now())
        });
        if (result.affected) {
            this.logger.debug(`Removed ${result.affected} outdated login refresh tokens for user`);
        }
    }
}

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