"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 AuditService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuditService = void 0;
const common_1 = require("@nestjs/common");
const event_emitter_1 = require("@nestjs/event-emitter");
const auth_config_service_1 = require("../../core/services/auth-config.service");
const auth_constants_1 = require("../../auth.constants");
const user_logged_in_event_1 = require("../../auth/events/user-logged-in.event");
const logged_out_event_1 = require("../../auth/events/logged-out.event");
const user_registered_event_1 = require("../../auth/events/user-registered.event");
const user_password_changed_event_1 = require("../../auth/events/user-password-changed.event");
const user_2fa_enabled_event_1 = require("../../auth/events/user-2fa-enabled.event");
const user_2fa_disabled_event_1 = require("../../auth/events/user-2fa-disabled.event");
let AuditService = AuditService_1 = class AuditService {
    authConfigService;
    logger = new common_1.Logger(AuditService_1.name);
    constructor(authConfigService) {
        this.authConfigService = authConfigService;
    }
    async emitAuditEvent(event) {
        const config = this.authConfigService.getConfig();
        if (config.audit?.enabled === false) {
            return;
        }
        if (config.audit?.onEvent) {
            try {
                await config.audit.onEvent(event);
            }
            catch (error) {
                this.logger.error(`Error in audit.onEvent hook: ${error.message}`, error.stack);
            }
        }
    }
    async handleUserLoggedIn(payload) {
        await this.emitAuditEvent({
            type: 'login',
            userId: payload.payload.user.id,
            ip: payload.payload.session.ipAddress,
            userAgent: payload.payload.session.userAgent,
            success: true,
            metadata: {
                provider: payload.payload.provider,
                tenantId: payload.payload.tenantId,
            },
            timestamp: new Date(),
        });
    }
    async handleUserLoggedOut(payload) {
        await this.emitAuditEvent({
            type: 'logout',
            userId: payload.payload.user?.id,
            success: true,
            metadata: {
                reason: payload.payload.reason,
                sessionId: payload.payload.session.id,
            },
            timestamp: new Date(),
        });
    }
    async handleUserRegistered(payload) {
        await this.emitAuditEvent({
            type: 'signup',
            userId: payload.payload.user.id,
            success: true,
            metadata: {
                tenantId: payload.payload.tenantId,
                provider: payload.payload.provider,
            },
            timestamp: new Date(),
        });
    }
    async handlePasswordChanged(payload) {
        await this.emitAuditEvent({
            type: 'password_change',
            userId: payload.payload.user.id,
            success: true,
            metadata: {
                initiatedBy: payload.payload.initiatedBy,
            },
            timestamp: new Date(),
        });
    }
    async handle2faEnabled(payload) {
        await this.emitAuditEvent({
            type: 'mfa_enable',
            userId: payload.payload.user.id,
            success: true,
            metadata: {
                method: payload.payload.method,
                action: 'enabled'
            },
            timestamp: new Date(),
        });
    }
    async handle2faDisabled(payload) {
        await this.emitAuditEvent({
            type: 'mfa_enable',
            userId: payload.payload.user.id,
            success: true,
            metadata: {
                action: 'disabled'
            },
            timestamp: new Date(),
        });
    }
};
exports.AuditService = AuditService;
__decorate([
    (0, event_emitter_1.OnEvent)(auth_constants_1.NestAuthEvents.LOGGED_IN),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [user_logged_in_event_1.UserLoggedInEvent]),
    __metadata("design:returntype", Promise)
], AuditService.prototype, "handleUserLoggedIn", null);
__decorate([
    (0, event_emitter_1.OnEvent)(auth_constants_1.NestAuthEvents.LOGGED_OUT),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [logged_out_event_1.LoggedOutEvent]),
    __metadata("design:returntype", Promise)
], AuditService.prototype, "handleUserLoggedOut", null);
__decorate([
    (0, event_emitter_1.OnEvent)(auth_constants_1.NestAuthEvents.REGISTERED),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [user_registered_event_1.UserRegisteredEvent]),
    __metadata("design:returntype", Promise)
], AuditService.prototype, "handleUserRegistered", null);
__decorate([
    (0, event_emitter_1.OnEvent)(auth_constants_1.NestAuthEvents.PASSWORD_CHANGED),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [user_password_changed_event_1.UserPasswordChangedEvent]),
    __metadata("design:returntype", Promise)
], AuditService.prototype, "handlePasswordChanged", null);
__decorate([
    (0, event_emitter_1.OnEvent)(auth_constants_1.NestAuthEvents.TWO_FACTOR_ENABLED),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [user_2fa_enabled_event_1.User2faEnabledEvent]),
    __metadata("design:returntype", Promise)
], AuditService.prototype, "handle2faEnabled", null);
__decorate([
    (0, event_emitter_1.OnEvent)(auth_constants_1.NestAuthEvents.TWO_FACTOR_DISABLED),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [user_2fa_disabled_event_1.User2faDisabledEvent]),
    __metadata("design:returntype", Promise)
], AuditService.prototype, "handle2faDisabled", null);
exports.AuditService = AuditService = AuditService_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [auth_config_service_1.AuthConfigService])
], AuditService);
//# sourceMappingURL=audit.service.js.map