"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); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SessionManagerService = exports.SESSION_REPOSITORY = exports.SESSION_STORE = void 0;
const common_1 = require("@nestjs/common");
const auth_config_service_1 = require("../../core/services/auth-config.service");
const request_context_1 = require("../../request-context/request-context");
const uuid_1 = require("uuid");
const ms_1 = __importDefault(require("ms"));
exports.SESSION_STORE = 'SESSION_STORE';
exports.SESSION_REPOSITORY = 'SESSION_REPOSITORY';
let SessionManagerService = class SessionManagerService {
    store;
    constructor(store) {
        this.store = store;
    }
    get options() {
        return auth_config_service_1.AuthConfigService.getOptions();
    }
    get maxSessionsPerUser() {
        return this.options.session?.maxSessionsPerUser || 10;
    }
    get slidingExpiration() {
        return this.options.session?.slidingExpiration ?? true;
    }
    async createSession(payload) {
        const { userId, refreshToken, data, userAgent, deviceName, ipAddress } = payload;
        await this.enforceMaxSessions(userId);
        const sessionPayload = {
            id: (0, uuid_1.v4)(),
            userId,
            refreshToken: refreshToken || '',
            data: data || {},
            expiresAt: this.calculateExpiration(),
            userAgent: userAgent || request_context_1.RequestContext.currentRequest()?.headers['user-agent'] || 'Unknown',
            deviceName: deviceName || request_context_1.RequestContext.getDeviceInfo().deviceName,
            ipAddress: ipAddress || request_context_1.RequestContext.getDeviceInfo().ipAddress,
            lastActive: new Date(),
        };
        const session = await this.store.create(sessionPayload);
        if (this.options.session?.onCreated) {
            const user = data?.user;
            await this.options.session.onCreated(session, user);
        }
        return session;
    }
    async getSession(sessionId, refreshSession = true) {
        const session = await this.store.findById(sessionId);
        if (!session) {
            throw new common_1.UnauthorizedException('Session not found');
        }
        if (this.isExpired(session)) {
            await this.store.delete(sessionId);
            throw new common_1.UnauthorizedException('Session expired');
        }
        if (refreshSession && this.slidingExpiration) {
            await this.touchSession(sessionId);
        }
        return session;
    }
    async getUserSessions(userId) {
        return await this.store.findByUserId(userId);
    }
    async getActiveSessions(userId) {
        return await this.store.findActiveByUserId(userId);
    }
    async updateSession(sessionId, updates) {
        return await this.store.update(sessionId, updates);
    }
    async revokeSession(sessionId) {
        let session = null;
        if (this.options.session?.onRevoked) {
            session = await this.store.findById(sessionId);
        }
        await this.store.delete(sessionId);
        if (this.options.session?.onRevoked && session) {
            await this.options.session.onRevoked(session, 'admin');
        }
    }
    async deleteSession(sessionId) {
        await this.revokeSession(sessionId);
    }
    async revokeAllUserSessions(userId) {
        await this.store.deleteByUserId(userId);
    }
    async revokeOtherSessions(userId, currentSessionId) {
        const sessions = await this.store.findByUserId(userId);
        for (const session of sessions) {
            if (session.id !== currentSessionId) {
                await this.store.delete(session.id);
            }
        }
    }
    async cleanupExpiredSessions() {
        return await this.store.deleteExpired();
    }
    async extendSession(sessionId, duration) {
        const expiresAt = this.calculateExpiration(duration);
        return await this.store.update(sessionId, { expiresAt });
    }
    async touchSession(sessionId, duration) {
        const expiresAt = this.calculateExpiration(duration);
        return await this.store.update(sessionId, {
            lastActive: new Date(),
            expiresAt,
        });
    }
    async rotateSession(sessionId) {
        const session = await this.store.findById(sessionId);
        if (!session) {
            throw new common_1.UnauthorizedException('Session not found');
        }
        const newSessionPayload = {
            id: (0, uuid_1.v4)(),
            userId: session.userId,
            refreshToken: session.refreshToken,
            data: session.data,
            expiresAt: this.calculateExpiration(),
            userAgent: session.userAgent,
            deviceName: session.deviceName,
            ipAddress: session.ipAddress,
            lastActive: new Date(),
        };
        const newSession = await this.store.create(newSessionPayload);
        await this.store.delete(sessionId);
        if (this.options.session?.onRevoked) {
            await this.options.session.onRevoked(session, 'security');
        }
        return newSession;
    }
    async validateSession(sessionId) {
        try {
            return await this.getSession(sessionId, true);
        }
        catch {
            return null;
        }
    }
    async hasReachedMaxSessions(userId) {
        const count = await this.store.countActiveByUserId(userId);
        return count >= this.maxSessionsPerUser;
    }
    async enforceMaxSessions(userId) {
        const activeSessions = await this.store.findActiveByUserId(userId);
        if (activeSessions.length >= this.maxSessionsPerUser) {
            const sorted = activeSessions.sort((a, b) => {
                const aTime = a.lastActive?.getTime() || 0;
                const bTime = b.lastActive?.getTime() || 0;
                return aTime - bTime;
            });
            const toRemove = sorted.slice(0, activeSessions.length - this.maxSessionsPerUser + 1);
            for (const session of toRemove) {
                await this.store.delete(session.id);
            }
        }
    }
    calculateExpiration(duration) {
        const expiryDuration = duration || this.options.session?.sessionExpiry || '7d';
        let milliseconds;
        if (typeof expiryDuration === 'string') {
            const parsed = (0, ms_1.default)(expiryDuration);
            if (parsed === undefined || !Number.isFinite(parsed) || parsed <= 0) {
                milliseconds = (0, ms_1.default)('7d') || 7 * 24 * 60 * 60 * 1000;
            }
            else {
                milliseconds = parsed;
            }
        }
        else {
            milliseconds = expiryDuration * 1000;
            if (!Number.isFinite(milliseconds) || milliseconds <= 0) {
                throw new Error(`Invalid session expiry duration: ${expiryDuration} seconds`);
            }
        }
        return new Date(Date.now() + milliseconds);
    }
    isExpired(session) {
        if (!session.expiresAt)
            return false;
        return new Date() > new Date(session.expiresAt);
    }
    async createSessionFromUser(user, extraData = {}) {
        const { deviceName, ipAddress, browser } = request_context_1.RequestContext.getDeviceInfo();
        const { isMfaVerified = false } = extraData;
        if (!user) {
            throw new common_1.UnauthorizedException('User not found');
        }
        const roles = await user.getRoles();
        const permissions = await user.getPermissions();
        let sessionData = {
            user,
            isMfaVerified,
            roles,
            permissions,
        };
        if (this.options.session?.customizeSessionData) {
            sessionData = await this.options.session.customizeSessionData(sessionData, user);
        }
        return await this.createSession({
            userId: user.id,
            data: sessionData,
            userAgent: [browser, deviceName].join(' - '),
            ipAddress,
            deviceName,
        });
    }
    async refreshSession(session) {
        const updates = {
            expiresAt: this.calculateExpiration(),
            lastActive: new Date(),
        };
        if (this.options.session?.onRefreshed) {
            const newSession = { ...session, ...updates };
            await this.options.session.onRefreshed(session, newSession);
        }
        return await this.updateSession(session.id, updates);
    }
    async getCurrentSessions(userId) {
        return await this.getActiveSessions(userId);
    }
};
exports.SessionManagerService = SessionManagerService;
exports.SessionManagerService = SessionManagerService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, common_1.Inject)(exports.SESSION_STORE)),
    __metadata("design:paramtypes", [Object])
], SessionManagerService);
//# sourceMappingURL=session-manager.service.js.map