"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"));
const role_mapper_util_1 = require("../../role/utils/role-mapper.util");
const lodash_1 = require("lodash");
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 ?? false;
    }
    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;
    }
    shouldTouchSession(session) {
        const now = Date.now();
        const lastActive = session.lastActive ? new Date(session.lastActive).getTime() : 0;
        const touchedRecently = now - lastActive < this.getTouchIntervalMs();
        return !touchedRecently;
    }
    getTouchIntervalMs() {
        const raw = this.options.session?.touchInterval ?? '5m';
        return typeof raw === 'string' ? (0, ms_1.default)(raw) : raw;
    }
    async getSession(sessionId) {
        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 (this.slidingExpiration && this.shouldTouchSession(session)) {
            const updatedSession = await this.touchSession(sessionId);
            return updatedSession;
        }
        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, reason = 'admin') {
        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, reason);
        }
    }
    async deleteSession(sessionId, reason = 'admin') {
        await this.revokeSession(sessionId, reason);
    }
    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 touchSession(sessionId) {
        const expiresAt = this.calculateExpiration();
        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);
        }
        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() {
        const expiryDuration = this.options.session?.refreshTokenValidity;
        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, userAccess, extraData = {}) {
        const { deviceName, ipAddress, browser } = request_context_1.RequestContext.getDeviceInfo();
        const { isMfaVerified = false, tenantId = null, isPlatformAccess } = extraData;
        if (!user) {
            throw new common_1.UnauthorizedException('User not found');
        }
        let roles = [];
        let permissions = [];
        if (isPlatformAccess) {
            roles = extraData?.platformAccess?.roles ?? [];
        }
        else {
            roles = userAccess?.roles ?? [];
        }
        permissions = (0, lodash_1.chain)(roles)
            .map((role) => (0, role_mapper_util_1.getRolePermissionNames)(role))
            .flatten()
            .uniq()
            .value();
        let sessionData = {
            user,
            isMfaVerified,
            roles: roles.map((role) => (0, role_mapper_util_1.mapRoleToSessionSnapshot)(role)),
            permissions,
            tenantId,
            isPlatformAccess: isPlatformAccess ?? false,
        };
        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