"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 __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RefreshTokenIdsStorageService = exports.InvalidatedRefreshTokenError = void 0;
const cache_manager_1 = require("@nestjs/cache-manager");
const common_1 = require("@nestjs/common");
const authentication_service_1 = require("./authentication.service");
class InvalidatedRefreshTokenError extends Error {
}
exports.InvalidatedRefreshTokenError = InvalidatedRefreshTokenError;
let RefreshTokenIdsStorageService = class RefreshTokenIdsStorageService {
    constructor(cacheManager, authenticationService) {
        this.cacheManager = cacheManager;
        this.authenticationService = authenticationService;
    }
    async insert(userId, refreshToken, previousRefreshToken) {
        const existing = (await this.cacheManager.get(this.getKey(userId)));
        const refreshTokenState = {
            currentRefreshToken: refreshToken,
            previousRefreshToken: previousRefreshToken ?? "",
        };
        await this.cacheManager.set(this.getKey(userId), refreshTokenState);
    }
    async validate(userId, refreshToken) {
        const storedId = await this.cacheManager.get(this.getKey(userId));
        if (storedId !== refreshToken) {
            throw new InvalidatedRefreshTokenError();
        }
        return storedId === refreshToken;
    }
    async invalidate(userId) {
        await this.cacheManager.del(this.getKey(userId));
    }
    async validateAndRotate(user, refreshToken) {
        let valid = false;
        const refreshTokenState = await this.cacheManager.get(this.getKey(user.id));
        console.log("refreshTokenState", refreshTokenState);
        let newRefreshToken;
        if (refreshTokenState &&
            typeof refreshTokenState === 'object' &&
            'currentRefreshToken' in refreshTokenState &&
            'previousRefreshToken' in refreshTokenState) {
            if (refreshTokenState.currentRefreshToken === refreshToken) {
                valid = true;
                newRefreshToken = await this.authenticationService.generateRefreshToken(user, refreshTokenState.currentRefreshToken);
                setTimeout(async () => {
                    const state = (await this.cacheManager.get(this.getKey(user.id)));
                    if (state && state.currentRefreshToken === newRefreshToken) {
                        await this.cacheManager.set(this.getKey(user.id), {
                            currentRefreshToken: newRefreshToken,
                            previousRefreshToken: "",
                        });
                    }
                }, 1 * 60 * 1000);
            }
            else if (refreshTokenState.previousRefreshToken === refreshToken) {
                valid = true;
                const existingRefreshTokenState = (await this.cacheManager.get(this.getKey(user.id)));
                newRefreshToken = existingRefreshTokenState?.currentRefreshToken;
            }
        }
        if (!valid) {
            throw new InvalidatedRefreshTokenError();
        }
        return newRefreshToken;
    }
    getKey(userId) {
        return `user-${userId}`;
    }
    getCurrentRefreshTokenState(userId) {
        return this.cacheManager.get(this.getKey(userId));
    }
};
exports.RefreshTokenIdsStorageService = RefreshTokenIdsStorageService;
exports.RefreshTokenIdsStorageService = RefreshTokenIdsStorageService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, common_1.Inject)(cache_manager_1.CACHE_MANAGER)),
    __param(1, (0, common_1.Inject)((0, common_1.forwardRef)(() => authentication_service_1.AuthenticationService))),
    __metadata("design:paramtypes", [Object, authentication_service_1.AuthenticationService])
], RefreshTokenIdsStorageService);
//# sourceMappingURL=refresh-token-ids-storage.service.js.map