"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 = 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_REPOSITORY = 'SESSION_REPOSITORY';
let SessionManagerService = class SessionManagerService {
    repository;
    constructor(repository) {
        this.repository = repository;
    }
    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.repository.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.repository.findById(sessionId);
        if (!session) {
            throw new common_1.UnauthorizedException('Session not found');
        }
        if (this.isExpired(session)) {
            await this.repository.delete(sessionId);
            throw new common_1.UnauthorizedException('Session expired');
        }
        if (refreshSession && this.slidingExpiration) {
            await this.repository.updateLastActive(sessionId);
        }
        return session;
    }
    async getUserSessions(userId) {
        return await this.repository.findByUserId(userId);
    }
    async getActiveSessions(userId) {
        return await this.repository.findActiveByUserId(userId);
    }
    async updateSession(sessionId, updates) {
        return await this.repository.update(sessionId, updates);
    }
    async revokeSession(sessionId) {
        let session = null;
        if (this.options.session?.onRevoked) {
            session = await this.repository.findById(sessionId);
        }
        await this.repository.delete(sessionId);
        if (this.options.session?.onRevoked && session) {
            await this.options.session.onRevoked(session, 'admin');
        }
    }
    async revokeAllUserSessions(userId) {
        await this.repository.deleteByUserId(userId);
    }
    async revokeOtherSessions(userId, currentSessionId) {
        const sessions = await this.repository.findByUserId(userId);
        for (const session of sessions) {
            if (session.id !== currentSessionId) {
                await this.repository.delete(session.id);
            }
        }
    }
    async cleanupExpiredSessions() {
        return await this.repository.deleteExpired();
    }
    async extendSession(sessionId, duration) {
        const expiresAt = this.calculateExpiration(duration);
        return await this.repository.update(sessionId, { expiresAt });
    }
    async validateSession(sessionId) {
        try {
            return await this.getSession(sessionId, true);
        }
        catch {
            return null;
        }
    }
    async hasReachedMaxSessions(userId) {
        const count = await this.repository.countActiveByUserId(userId);
        return count >= this.maxSessionsPerUser;
    }
    async enforceMaxSessions(userId) {
        const activeSessions = await this.repository.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.repository.delete(session.id);
            }
        }
    }
    calculateExpiration(duration) {
        const expiryDuration = duration || this.options.session?.sessionExpiry || '7d';
        const milliseconds = (0, ms_1.default)(expiryDuration);
        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_REPOSITORY)),
    __metadata("design:paramtypes", [Object])
], SessionManagerService);
//# sourceMappingURL=session-manager.service.js.map