"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.AuthService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const user_entity_1 = require("../../user/entities/user.entity");
const otp_entity_1 = require("../../auth/entities/otp.entity");
const otp_interface_1 = require("../../core/interfaces/otp.interface");
const auth_constants_1 = require("../../auth.constants");
const typeorm_3 = require("typeorm");
const mfa_service_1 = require("./mfa.service");
const jwt_service_1 = require("../../core/services/jwt.service");
const event_emitter_1 = require("@nestjs/event-emitter");
const session_manager_service_1 = require("../../session/services/session-manager.service");
const request_context_1 = require("../../request-context/request-context");
const otp_1 = require("../../utils/otp");
const user_registered_event_1 = require("../events/user-registered.event");
const user_logged_in_event_1 = require("../events/user-logged-in.event");
const user_2fa_verified_event_1 = require("../events/user-2fa-verified.event");
const user_refresh_token_event_1 = require("../events/user-refresh-token.event");
const logged_out_event_1 = require("../events/logged-out.event");
const logged_out_all_event_1 = require("../events/logged-out-all.event");
const password_reset_requested_event_1 = require("../events/password-reset-requested.event");
const password_reset_event_1 = require("../events/password-reset.event");
const auth_provider_registry_service_1 = require("../../core/services/auth-provider-registry.service");
const tenant_service_1 = require("../../tenant/services/tenant.service");
const debug_logger_service_1 = require("../../core/services/debug-logger.service");
const moment_1 = __importDefault(require("moment"));
const auth_config_service_1 = require("../../core/services/auth-config.service");
const cookie_helper_1 = require("../../utils/cookie.helper");
const user_password_changed_event_1 = require("../events/user-password-changed.event");
const user_service_1 = require("../../user/services/user.service");
const ms_1 = __importDefault(require("ms"));
let AuthService = class AuthService {
    userRepository;
    otpRepository;
    authProviderRegistry;
    mfaService;
    sessionManager;
    jwtService;
    eventEmitter;
    tenantService;
    debugLogger;
    authConfigService;
    userService;
    constructor(userRepository, otpRepository, authProviderRegistry, mfaService, sessionManager, jwtService, eventEmitter, tenantService, debugLogger, authConfigService, userService) {
        this.userRepository = userRepository;
        this.otpRepository = otpRepository;
        this.authProviderRegistry = authProviderRegistry;
        this.mfaService = mfaService;
        this.sessionManager = sessionManager;
        this.jwtService = jwtService;
        this.eventEmitter = eventEmitter;
        this.tenantService = tenantService;
        this.debugLogger = debugLogger;
        this.authConfigService = authConfigService;
        this.userService = userService;
    }
    get mfaConfig() {
        return auth_config_service_1.AuthConfigService.getOptions().mfa || {};
    }
    getUserWithRolesAndPermissions(userId, relations = []) {
        return this.userRepository.findOne({
            where: { id: userId },
            relations: [
                'roles',
                ...relations
            ],
        });
    }
    async getUser() {
        const user = request_context_1.RequestContext.currentUser();
        if (!user) {
            return null;
        }
        const fullUser = await this.getUserWithRolesAndPermissions(user.id);
        const config = this.authConfigService.getConfig();
        if (config.user?.serialize) {
            return await config.user.serialize(fullUser);
        }
        return fullUser;
    }
    async signup(input) {
        this.debugLogger.logFunctionEntry('signup', 'AuthService', { email: input.email, phone: input.phone, hasPassword: !!input.password });
        try {
            const config = this.authConfigService.getConfig();
            if (config.registration?.enabled === false) {
                throw new common_1.ForbiddenException({
                    message: 'Registration is disabled',
                    code: auth_constants_1.ERROR_CODES.REGISTRATION_DISABLED,
                });
            }
            const { email, phone, password } = input;
            let { tenantId = null } = input;
            tenantId = await this.tenantService.resolveTenantId(tenantId);
            this.debugLogger.logAuthOperation('signup', 'email|phone', undefined, { email, phone, resolvedTenantId: tenantId });
            if (!email && !phone) {
                this.debugLogger.error('Signup failed: Neither email nor phone provided', 'AuthService');
                throw new common_1.BadRequestException({
                    message: 'Either email or phone must be provided',
                    code: auth_constants_1.ERROR_CODES.EMAIL_OR_PHONE_REQUIRED,
                });
            }
            const providersToLink = [];
            if (email && config.emailAuth?.enabled !== false) {
                const provider = this.authProviderRegistry.getProvider(auth_constants_1.EMAIL_AUTH_PROVIDER);
                if (provider) {
                    providersToLink.push({ provider, userId: email, type: 'email' });
                }
            }
            if (phone && config.phoneAuth?.enabled === true) {
                const provider = this.authProviderRegistry.getProvider(auth_constants_1.PHONE_AUTH_PROVIDER);
                if (provider) {
                    providersToLink.push({ provider, userId: phone, type: 'phone' });
                }
            }
            if (providersToLink.length === 0) {
                this.debugLogger.error('Provider not found for signup', 'AuthService', { email: !!email, phone: !!phone });
                throw new common_1.InternalServerErrorException({
                    message: 'Phone or email authentication is not enabled',
                    code: auth_constants_1.ERROR_CODES.PROVIDER_NOT_FOUND,
                });
            }
            for (const item of providersToLink) {
                this.debugLogger.debug('Checking for existing identity', 'AuthService', { providerUserId: item.userId, type: item.type });
                const identity = await item.provider.findIdentity(item.userId);
                if (identity) {
                    this.debugLogger.warn('Identity already exists', 'AuthService', { email: !!email, phone: !!phone, tenantId });
                    if (item.type === 'email') {
                        throw new common_1.BadRequestException({
                            message: 'Email already exists in this tenant',
                            code: auth_constants_1.ERROR_CODES.EMAIL_ALREADY_EXISTS,
                        });
                    }
                    if (item.type === 'phone') {
                        throw new common_1.BadRequestException({
                            message: 'Phone number already exists in this tenant',
                            code: auth_constants_1.ERROR_CODES.PHONE_ALREADY_EXISTS,
                        });
                    }
                }
            }
            this.debugLogger.debug('Creating new user via UserService', 'AuthService', { email: !!email, phone: !!phone, tenantId });
            let user = await this.userService.createUser({
                email,
                phone,
                tenantId,
                isVerified: false,
                password
            }, input);
            this.debugLogger.info('User created successfully', 'AuthService', { userId: user.id, tenantId });
            user = await this.getUserWithRolesAndPermissions(user.id);
            for (const item of providersToLink) {
                this.debugLogger.debug('Linking user to provider', 'AuthService', { userId: user.id, providerName: item.provider.providerName });
                await item.provider.linkToUser(user.id, item.userId);
            }
            this.debugLogger.debug('Creating session for new user', 'AuthService', { userId: user.id });
            const session = await this.sessionManager.createSessionFromUser(user);
            const tokens = await this.generateTokensFromSession(session);
            const isRequiresMfa = await this.mfaService.isRequiresMfa(user.id);
            this.debugLogger.debug('Signup tokens generated', 'AuthService', { userId: user.id, isRequiresMfa });
            this.debugLogger.debug('Emitting user registration event', 'AuthService', { userId: user.id });
            const provider = providersToLink[0]?.provider;
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.REGISTERED, new user_registered_event_1.UserRegisteredEvent({
                user,
                tenantId: user.tenantId,
                input,
                provider,
                session,
                tokens,
                isRequiresMfa
            }));
            this.debugLogger.logFunctionExit('signup', 'AuthService', { userId: user.id, isRequiresMfa });
            let response = {
                accessToken: tokens.accessToken,
                refreshToken: tokens.refreshToken,
                isRequiresMfa: isRequiresMfa,
            };
            if (config.auth?.transformResponse) {
                response = await config.auth.transformResponse(response, user, session);
            }
            return response;
        }
        catch (error) {
            this.debugLogger.logError(error, 'signup', { email: input.email, phone: input.phone });
            this.handleError(error, 'signup');
            throw error;
        }
    }
    async login(input) {
        const { credentials, providerName, createUserIfNotExists = false } = input;
        this.debugLogger.logFunctionEntry('login', 'AuthService', { providerName, createUserIfNotExists });
        let { tenantId = null } = input;
        try {
            tenantId = await this.tenantService.resolveTenantId(tenantId);
            this.debugLogger.logAuthOperation('login', providerName, undefined, { resolvedTenantId: tenantId, createUserIfNotExists });
            const provider = this.authProviderRegistry.getProvider(providerName);
            if (!provider) {
                throw new common_1.UnauthorizedException({
                    message: 'Invalid authentication providerName or provider is not enabled',
                    code: auth_constants_1.ERROR_CODES.INVALID_PROVIDER,
                });
            }
            const requiredFields = provider.getRequiredFields();
            if (!requiredFields.every(field => credentials[field])) {
                throw new common_1.BadRequestException({
                    message: `Missing ${requiredFields.join(', ')} required fields`,
                    code: auth_constants_1.ERROR_CODES.MISSING_REQUIRED_FIELDS,
                });
            }
            const authProviderUser = await provider.validate(credentials);
            const identity = await provider.findIdentity(authProviderUser.userId);
            let user = identity?.user || null;
            if (!user) {
                if (!createUserIfNotExists) {
                    throw new common_1.UnauthorizedException({
                        message: 'Invalid credentials',
                        code: auth_constants_1.ERROR_CODES.INVALID_CREDENTIALS,
                    });
                }
                user = await this.handleSocialLogin(provider, authProviderUser, tenantId);
            }
            if (user.isActive === false) {
                throw new common_1.UnauthorizedException({
                    message: 'Your account is suspended, please contact support',
                    code: auth_constants_1.ERROR_CODES.ACCOUNT_INACTIVE,
                });
            }
            user = await this.getUserWithRolesAndPermissions(user.id);
            let isRequiresMfa = false;
            if (!provider.skipMfa) {
                isRequiresMfa = await this.mfaService.isRequiresMfa(user.id);
            }
            user.isMfaEnabled = isRequiresMfa;
            let session = await this.sessionManager.createSessionFromUser(user);
            if (isRequiresMfa) {
                const trustCookieName = auth_config_service_1.AuthConfigService.getOptions().mfa?.trustDeviceStorageName || auth_constants_1.NEST_AUTH_TRUST_DEVICE_KEY;
                const req = request_context_1.RequestContext.currentRequest();
                let trustToken = cookie_helper_1.CookieHelper.get(req, trustCookieName);
                if (!trustToken) {
                    trustToken = req.headers[trustCookieName];
                }
                let isTrusted = false;
                if (trustToken) {
                    isTrusted = await this.mfaService.validateTrustedDevice(user.id, trustToken);
                    if (isTrusted) {
                        isRequiresMfa = false;
                        session = await this.sessionManager.updateSession(session.id, {
                            data: { ...session.data, isMfaVerified: true }
                        });
                    }
                }
                session = await this.sessionManager.updateSession(session.id, {
                    data: { ...session.data, isMfaEnabled: true, isMfaVerified: isTrusted }
                });
            }
            const tokens = await this.generateTokensFromSession(session);
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.LOGGED_IN, new user_logged_in_event_1.UserLoggedInEvent({
                user,
                tenantId: user.tenantId,
                input,
                provider,
                session,
                tokens,
                isRequiresMfa
            }));
            let response = {
                accessToken: tokens.accessToken,
                refreshToken: tokens.refreshToken,
                isRequiresMfa: isRequiresMfa,
            };
            const config = this.authConfigService.getConfig();
            if (config.auth?.transformResponse) {
                response = await config.auth.transformResponse(response, user, session);
            }
            return response;
        }
        catch (error) {
            this.debugLogger.logError(error, 'login', { providerName, createUserIfNotExists });
            this.handleError(error, 'login');
            throw error;
        }
    }
    async verify2fa(input) {
        this.debugLogger.logFunctionEntry('verify2fa', 'AuthService', { method: input.method });
        try {
            const session = request_context_1.RequestContext.currentSession();
            if (!session) {
                this.debugLogger.error('Session not found for 2FA verification', 'AuthService');
                throw new common_1.UnauthorizedException({
                    message: 'Session not found',
                    code: auth_constants_1.ERROR_CODES.SESSION_NOT_FOUND,
                });
            }
            this.debugLogger.debug('Verifying MFA code', 'AuthService', { userId: session.userId, method: input.method });
            const isValid = await this.mfaService.verifyMfa(session.userId, input.otp, input.method);
            if (!isValid) {
                this.debugLogger.warn('Invalid MFA code provided', 'AuthService', { userId: session.userId, method: input.method });
                throw new common_1.UnauthorizedException({
                    message: 'Invalid MFA code',
                    code: auth_constants_1.ERROR_CODES.MFA_CODE_INVALID,
                });
            }
            this.debugLogger.debug('Updating session with MFA verification', 'AuthService', { sessionId: session.id });
            const payload = await this.sessionManager.updateSession(session.id, {
                data: {
                    ...session.data,
                    isMfaVerified: true,
                }
            });
            const tokens = await this.generateTokensFromSession(payload);
            let trustToken;
            if (input.rememberDevice) {
                const req = request_context_1.RequestContext.currentRequest();
                const userAgent = req.headers['user-agent'] || '';
                const ip = req.ip || req.socket.remoteAddress || '';
                trustToken = await this.mfaService.createTrustedDevice(session.userId, userAgent, ip);
            }
            const user = await this.getUser();
            this.debugLogger.debug('Emitting 2FA verified event', 'AuthService', { userId: user.id });
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.TWO_FACTOR_VERIFIED, new user_2fa_verified_event_1.User2faVerifiedEvent({
                user: user,
                tenantId: user.tenantId,
                input,
                session,
                tokens
            }));
            this.debugLogger.logFunctionExit('verify2fa', 'AuthService', { userId: user.id });
            return {
                accessToken: tokens.accessToken,
                refreshToken: tokens.refreshToken,
                trustToken,
            };
        }
        catch (error) {
            this.debugLogger.logError(error, 'verify2fa', { method: input.method });
            this.handleError(error, 'mfa');
            throw error;
        }
    }
    async send2faCode(userId, method) {
        const user = await this.userRepository.findOne({ where: { id: userId } });
        if (!user) {
            throw new common_1.UnauthorizedException({
                message: 'User not found',
                code: auth_constants_1.ERROR_CODES.USER_NOT_FOUND,
            });
        }
        await this.mfaService.sendMfaCode(user.id, method);
        return true;
    }
    async handleSocialLogin(provider, providerUser, tenantId) {
        let identity = await provider.findIdentity(providerUser.userId);
        if (identity) {
            return identity.user;
        }
        const linkUserWith = provider.linkUserWith();
        const linkUserValue = providerUser?.[linkUserWith] || providerUser.userId;
        let user = await this.userRepository.findOne({ where: { [linkUserWith]: linkUserValue } });
        if (!user) {
            try {
                user = await this.userService.createUser({
                    [linkUserWith]: linkUserValue,
                    isVerified: true,
                    metadata: providerUser.metadata || {},
                    tenantId: tenantId,
                }, {
                    [linkUserWith]: linkUserValue,
                    ...providerUser,
                    firstName: providerUser.metadata?.name?.split(' ')[0],
                    lastName: providerUser.metadata?.name?.split(' ').slice(1).join(' '),
                    provider: provider.providerName,
                    description: 'Social login auto-creation'
                });
            }
            catch (error) {
                if (error instanceof common_1.ConflictException || error.status === 409) {
                    user = await this.userRepository.findOne({ where: { [linkUserWith]: linkUserValue } });
                    if (!user) {
                        throw error;
                    }
                }
                else {
                    throw error;
                }
            }
        }
        await provider.linkToUser(user.id, providerUser.userId, providerUser.metadata || {});
        return user;
    }
    async refreshToken(refreshToken) {
        this.debugLogger.logFunctionEntry('refreshToken', 'AuthService', { hasRefreshToken: !!refreshToken });
        try {
            if (!refreshToken) {
                this.debugLogger.error('No refresh token provided', 'AuthService');
                throw new common_1.UnauthorizedException({
                    message: 'No refresh token provided',
                    code: auth_constants_1.ERROR_CODES.REFRESH_TOKEN_INVALID,
                });
            }
            this.debugLogger.debug('Verifying refresh token', 'AuthService');
            let payload;
            try {
                payload = await this.jwtService.verifyToken(refreshToken);
            }
            catch (error) {
                this.debugLogger.warn('Invalid or expired refresh token', 'AuthService');
                throw new common_1.UnauthorizedException({
                    message: 'Invalid or expired refresh token',
                    code: auth_constants_1.ERROR_CODES.REFRESH_TOKEN_EXPIRED,
                });
            }
            const session = await this.sessionManager.getSession(payload.sessionId);
            if (!session) {
                throw new common_1.UnauthorizedException({
                    message: 'Invalid refresh token',
                    code: auth_constants_1.ERROR_CODES.REFRESH_TOKEN_INVALID,
                });
            }
            const newSession = await this.sessionManager.refreshSession(session);
            this.debugLogger.debug('Generating new tokens from refreshed session', 'AuthService', { sessionId: newSession.id });
            const tokens = await this.generateTokensFromSession(newSession);
            this.debugLogger.debug('Emitting refresh token event', 'AuthService', { sessionId: newSession.id });
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.REFRESH_TOKEN, new user_refresh_token_event_1.UserRefreshTokenEvent({
                oldRefreshToken: refreshToken,
                session: newSession,
                tokens,
            }));
            this.debugLogger.logFunctionExit('refreshToken', 'AuthService', { sessionId: newSession.id });
            return tokens;
        }
        catch (error) {
            this.debugLogger.logError(error, 'refreshToken', { hasRefreshToken: !!refreshToken });
            this.handleError(error, 'refresh');
            throw error;
        }
    }
    async changePassword(input) {
        this.debugLogger.logFunctionEntry('changePassword', 'AuthService');
        try {
            const currentUser = request_context_1.RequestContext.currentUser();
            if (!currentUser?.id) {
                throw new common_1.UnauthorizedException({
                    message: 'User not found',
                    code: auth_constants_1.ERROR_CODES.USER_NOT_FOUND,
                });
            }
            const user = await this.userRepository.findOne({
                where: { id: currentUser.id },
            });
            if (!user) {
                throw new common_1.UnauthorizedException({
                    message: 'User not found',
                    code: auth_constants_1.ERROR_CODES.USER_NOT_FOUND,
                });
            }
            const isValid = await user.validatePassword(input.currentPassword);
            if (!isValid) {
                throw new common_1.BadRequestException({
                    message: 'Current password is incorrect',
                    code: auth_constants_1.ERROR_CODES.CURRENT_PASSWORD_INCORRECT,
                });
            }
            if (input.currentPassword === input.newPassword) {
                throw new common_1.BadRequestException({
                    message: 'New password must be different from the current password',
                    code: auth_constants_1.ERROR_CODES.NEW_PASSWORD_SAME_AS_CURRENT,
                });
            }
            await user.setPassword(input.newPassword);
            await this.userRepository.save(user);
            await this.sessionManager.revokeAllUserSessions(user.id);
            const hydratedUser = await this.getUserWithRolesAndPermissions(user.id);
            const session = await this.sessionManager.createSessionFromUser(hydratedUser);
            const tokens = await this.generateTokensFromSession(session);
            const isRequiresMfa = await this.mfaService.isRequiresMfa(user.id);
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.PASSWORD_CHANGED, new user_password_changed_event_1.UserPasswordChangedEvent({
                user,
                initiatedBy: 'user'
            }));
            this.debugLogger.logFunctionExit('changePassword', 'AuthService', { userId: user.id });
            return {
                accessToken: tokens.accessToken,
                refreshToken: tokens.refreshToken,
                isRequiresMfa,
            };
        }
        catch (error) {
            this.debugLogger.logError(error, 'changePassword');
            this.handleError(error, 'password_change');
            throw error;
        }
    }
    async forgotPassword(input) {
        this.debugLogger.logFunctionEntry('forgotPassword', 'AuthService', { email: input.email, phone: input.phone });
        try {
            const { email, phone } = input;
            let { tenantId = null } = input;
            tenantId = await this.tenantService.resolveTenantId(tenantId);
            let provider = null;
            if (phone) {
                provider = this.authProviderRegistry.getProvider(auth_constants_1.PHONE_AUTH_PROVIDER);
            }
            else if (email) {
                provider = this.authProviderRegistry.getProvider(auth_constants_1.EMAIL_AUTH_PROVIDER);
            }
            else {
                throw new common_1.BadRequestException({
                    message: 'Either email or phone must be provided',
                    code: auth_constants_1.ERROR_CODES.EMAIL_OR_PHONE_REQUIRED,
                });
            }
            if (!provider) {
                throw new common_1.BadRequestException({
                    message: 'Phone or email authentication is not enabled',
                    code: auth_constants_1.ERROR_CODES.PROVIDER_NOT_FOUND,
                });
            }
            if (!provider.enabled) {
                if (email) {
                    throw new common_1.BadRequestException({
                        message: 'Email authentication is not enabled',
                        code: auth_constants_1.ERROR_CODES.PROVIDER_NOT_FOUND,
                    });
                }
                else if (phone) {
                    throw new common_1.BadRequestException({
                        message: 'Phone authentication is not enabled',
                        code: auth_constants_1.ERROR_CODES.PROVIDER_NOT_FOUND,
                    });
                }
            }
            const identity = await provider.findIdentity(email || phone);
            if (!identity) {
                return { message: 'If the account exists, a password reset code has been sent' };
            }
            const options = auth_config_service_1.AuthConfigService.getOptions();
            let code;
            if (options.otp?.generate) {
                code = await options.otp.generate(this.mfaConfig.otpLength);
            }
            else {
                code = (0, otp_1.generateOtp)(this.mfaConfig.otpLength);
            }
            let expiresAtMs;
            if (typeof this.mfaConfig.otpExpiresIn === 'string') {
                expiresAtMs = (0, ms_1.default)(this.mfaConfig.otpExpiresIn);
            }
            else {
                expiresAtMs = this.mfaConfig.otpExpiresIn || 900000;
            }
            if (!expiresAtMs || isNaN(expiresAtMs) || expiresAtMs <= 0) {
                throw new Error(`Invalid MFA configuration: otpExpiresIn '${this.mfaConfig.otpExpiresIn}' results in invalid duration`);
            }
            await this.otpRepository.delete({
                userId: identity.user?.id,
                type: otp_interface_1.OTPTypeEnum.PASSWORD_RESET
            });
            const otpEntity = await this.otpRepository.create({
                userId: identity.user?.id,
                type: otp_interface_1.OTPTypeEnum.PASSWORD_RESET,
                expiresAt: new Date(Date.now() + expiresAtMs),
                code,
            });
            await this.otpRepository.save(otpEntity);
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.PASSWORD_RESET_REQUESTED, new password_reset_requested_event_1.PasswordResetRequestedEvent({
                user: identity.user,
                tenantId: identity.user?.tenantId,
                input,
                otp: otpEntity,
                provider,
            }));
            this.debugLogger.logFunctionExit('forgotPassword', 'AuthService', { email: !!email, phone: !!phone });
            return true;
        }
        catch (error) {
            this.debugLogger.logError(error, 'forgotPassword', { email: input.email, phone: input.phone });
            this.handleError(error, 'password_reset');
            throw error;
        }
    }
    async verifyForgotPasswordOtp(input) {
        this.debugLogger.logFunctionEntry('verifyForgotPasswordOtp', 'AuthService', { email: input.email, phone: input.phone });
        try {
            const { email, phone, otp } = input;
            let { tenantId = null } = input;
            tenantId = await this.tenantService.resolveTenantId(tenantId);
            if (!email && !phone) {
                throw new common_1.BadRequestException({
                    message: 'Either email or phone must be provided',
                    code: auth_constants_1.ERROR_CODES.EMAIL_OR_PHONE_REQUIRED,
                });
            }
            let provider = null;
            if (phone) {
                provider = this.authProviderRegistry.getProvider(auth_constants_1.PHONE_AUTH_PROVIDER);
            }
            else if (email) {
                provider = this.authProviderRegistry.getProvider(auth_constants_1.EMAIL_AUTH_PROVIDER);
            }
            if (!provider) {
                throw new common_1.BadRequestException({
                    message: 'Phone or email authentication is not enabled',
                    code: auth_constants_1.ERROR_CODES.PROVIDER_NOT_FOUND,
                });
            }
            const identity = await provider.findIdentity(email || phone);
            if (!identity) {
                throw new common_1.BadRequestException({
                    message: 'Invalid reset request',
                    code: auth_constants_1.ERROR_CODES.PASSWORD_RESET_INVALID_REQUEST,
                });
            }
            const validOtp = await this.otpRepository.findOne({
                where: {
                    userId: identity.user?.id,
                    code: otp,
                    type: otp_interface_1.OTPTypeEnum.PASSWORD_RESET,
                    used: false
                },
                relations: ['user']
            });
            if (!validOtp) {
                throw new common_1.BadRequestException({
                    message: 'Invalid OTP code',
                    code: auth_constants_1.ERROR_CODES.OTP_INVALID,
                });
            }
            if ((0, moment_1.default)(validOtp.expiresAt).isBefore(new Date())) {
                throw new common_1.BadRequestException({
                    message: 'OTP code expired',
                    code: auth_constants_1.ERROR_CODES.OTP_EXPIRED,
                });
            }
            const user = validOtp.user;
            const passwordHashPrefix = user.passwordHash ? user.passwordHash.substring(0, 10) : '';
            const resetToken = await this.jwtService.generatePasswordResetToken({
                userId: user.id,
                passwordHashPrefix,
                type: 'password-reset'
            });
            await this.otpRepository.remove(validOtp);
            this.debugLogger.logFunctionExit('verifyForgotPasswordOtp', 'AuthService', { email: input.email, phone: input.phone });
            return {
                message: 'OTP verified successfully',
                resetToken
            };
        }
        catch (error) {
            this.debugLogger.logError(error, 'verifyForgotPasswordOtp', { email: input.email, phone: input.phone });
            this.handleError(error, 'password_reset');
            throw error;
        }
    }
    async resetPassword(input) {
        this.debugLogger.logFunctionEntry('resetPassword', 'AuthService', { email: input.email, phone: input.phone });
        try {
            const { email, phone, otp, newPassword } = input;
            let { tenantId = null } = input;
            tenantId = await this.tenantService.resolveTenantId(tenantId);
            if (!email && !phone) {
                throw new common_1.BadRequestException({
                    message: 'Either email or phone must be provided',
                    code: auth_constants_1.ERROR_CODES.EMAIL_OR_PHONE_REQUIRED,
                });
            }
            const user = await this.userRepository.findOne({
                where: [
                    ...(email ? [{ email, tenantId }] : []),
                    ...(phone ? [{ phone, tenantId }] : [])
                ]
            });
            if (!user) {
                throw new common_1.BadRequestException({
                    message: 'Invalid reset request',
                    code: auth_constants_1.ERROR_CODES.PASSWORD_RESET_INVALID_REQUEST,
                });
            }
            const validOtp = await this.otpRepository.findOne({
                where: {
                    userId: user.id,
                    code: otp,
                    type: otp_interface_1.OTPTypeEnum.PASSWORD_RESET,
                    expiresAt: (0, typeorm_3.MoreThan)(new Date()),
                    used: false
                }
            });
            if (!validOtp) {
                throw new common_1.BadRequestException({
                    message: 'Invalid or expired OTP',
                    code: auth_constants_1.ERROR_CODES.OTP_INVALID,
                });
            }
            await user.setPassword(newPassword);
            await this.userRepository.save(user);
            validOtp.used = true;
            await this.otpRepository.save(validOtp);
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.PASSWORD_RESET, new password_reset_event_1.PasswordResetEvent({
                user,
                tenantId: user.tenantId,
                input,
            }));
            this.debugLogger.logFunctionExit('resetPassword', 'AuthService', { email: !!email, phone: !!phone });
            return true;
        }
        catch (error) {
            this.debugLogger.logError(error, 'resetPassword', { email: input.email, phone: input.phone });
            this.handleError(error, 'password_reset');
            throw error;
        }
    }
    async resetPasswordWithToken(input) {
        this.debugLogger.logFunctionEntry('resetPasswordWithToken', 'AuthService', { token: '***' });
        try {
            const { token, newPassword } = input;
            let decoded;
            try {
                decoded = await this.jwtService.verifyPasswordResetToken(token);
            }
            catch (error) {
                throw new common_1.BadRequestException({
                    message: 'Invalid or expired reset token',
                    code: auth_constants_1.ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID,
                });
            }
            if (decoded.type !== 'password-reset') {
                throw new common_1.BadRequestException({
                    message: 'Invalid token type',
                    code: auth_constants_1.ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID,
                });
            }
            const user = await this.userRepository.findOne({
                where: { id: decoded.userId }
            });
            if (!user) {
                throw new common_1.BadRequestException({
                    message: 'User not found',
                    code: auth_constants_1.ERROR_CODES.USER_NOT_FOUND,
                });
            }
            const currentPasswordHashPrefix = user.passwordHash ? user.passwordHash.substring(0, 10) : '';
            if (decoded.passwordHashPrefix !== currentPasswordHashPrefix) {
                throw new common_1.BadRequestException({
                    message: 'Reset token is no longer valid',
                    code: auth_constants_1.ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID,
                });
            }
            await user.setPassword(newPassword);
            await this.userRepository.save(user);
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.PASSWORD_RESET, new password_reset_event_1.PasswordResetEvent({
                user,
                tenantId: user.tenantId,
                input: { token, newPassword },
            }));
            this.debugLogger.logFunctionExit('resetPasswordWithToken', 'AuthService');
            return true;
        }
        catch (error) {
            this.debugLogger.logError(error, 'resetPasswordWithToken');
            this.handleError(error, 'password_reset');
            throw error;
        }
    }
    async logout(logoutType = 'user', reason) {
        const session = request_context_1.RequestContext.currentSession();
        const user = await this.getUser();
        await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.LOGGED_OUT, new logged_out_event_1.LoggedOutEvent({
            user: user,
            tenantId: user?.tenantId,
            session,
            logoutType,
            reason,
        }));
        if (session) {
            await this.sessionManager.revokeSession(session.id);
        }
        return true;
    }
    async logoutAll(userId, logoutType = 'user', reason) {
        const session = request_context_1.RequestContext.currentSession();
        if (!session) {
            throw new common_1.UnauthorizedException({
                message: 'Session not found',
                code: auth_constants_1.ERROR_CODES.SESSION_NOT_FOUND,
            });
        }
        const sessions = await this.sessionManager.getUserSessions(userId);
        await this.sessionManager.revokeAllUserSessions(userId);
        const user = await this.userRepository.findOne({ where: { id: userId } });
        if (user) {
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.LOGGED_OUT_ALL, new logged_out_all_event_1.LoggedOutAllEvent({
                user,
                tenantId: user.tenantId,
                logoutType,
                reason,
                currentSessionId: session.id,
                sessions,
            }));
        }
        return true;
    }
    async sendEmailVerification(input) {
        this.debugLogger.logFunctionEntry('sendEmailVerification', 'AuthService');
        try {
            const user = request_context_1.RequestContext.currentUser();
            if (!user) {
                throw new common_1.UnauthorizedException({
                    message: 'User not authenticated',
                    code: auth_constants_1.ERROR_CODES.UNAUTHORIZED,
                });
            }
            const fullUser = await this.getUserWithRolesAndPermissions(user.id);
            if (!fullUser.email) {
                throw new common_1.BadRequestException({
                    message: 'User does not have an email address',
                    code: auth_constants_1.ERROR_CODES.NO_EMAIL_ADDRESS,
                });
            }
            if (fullUser.emailVerifiedAt) {
                throw new common_1.BadRequestException({
                    message: 'Email is already verified',
                    code: auth_constants_1.ERROR_CODES.EMAIL_ALREADY_VERIFIED,
                });
            }
            const otp = (0, otp_1.generateOtp)();
            const expiresAt = new Date();
            expiresAt.setMinutes(expiresAt.getMinutes() + 30);
            const otpEntity = await this.otpRepository.save({
                userId: fullUser.id,
                code: otp,
                expiresAt,
                type: otp_interface_1.OTPTypeEnum.VERIFICATION
            });
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.EMAIL_VERIFICATION_REQUESTED, {
                user: fullUser,
                tenantId: fullUser.tenantId,
                otp: otpEntity,
            });
            this.debugLogger.logFunctionExit('sendEmailVerification', 'AuthService');
            return { message: 'Verification email sent successfully' };
        }
        catch (error) {
            this.debugLogger.logError(error, 'sendEmailVerification');
            this.handleError(error, 'signup');
            throw error;
        }
    }
    async verifyEmail(input) {
        this.debugLogger.logFunctionEntry('verifyEmail', 'AuthService');
        try {
            const user = request_context_1.RequestContext.currentUser();
            if (!user) {
                throw new common_1.UnauthorizedException({
                    message: 'User not authenticated',
                    code: auth_constants_1.ERROR_CODES.UNAUTHORIZED,
                });
            }
            const fullUser = await this.getUserWithRolesAndPermissions(user.id);
            if (!fullUser.email) {
                throw new common_1.BadRequestException({
                    message: 'User does not have an email address',
                    code: auth_constants_1.ERROR_CODES.NO_EMAIL_ADDRESS,
                });
            }
            if (fullUser.emailVerifiedAt) {
                throw new common_1.BadRequestException({
                    message: 'Email is already verified',
                    code: auth_constants_1.ERROR_CODES.EMAIL_ALREADY_VERIFIED,
                });
            }
            const validOtp = await this.otpRepository.findOne({
                where: {
                    userId: fullUser.id,
                    code: input.otp,
                    type: otp_interface_1.OTPTypeEnum.VERIFICATION,
                    used: false
                }
            });
            if (!validOtp) {
                throw new common_1.BadRequestException({
                    message: 'Invalid verification code',
                    code: auth_constants_1.ERROR_CODES.VERIFICATION_CODE_INVALID,
                });
            }
            if ((0, moment_1.default)(validOtp.expiresAt).isBefore(new Date())) {
                throw new common_1.BadRequestException({
                    message: 'Verification code has expired',
                    code: auth_constants_1.ERROR_CODES.VERIFICATION_CODE_EXPIRED,
                });
            }
            validOtp.used = true;
            await this.otpRepository.save(validOtp);
            fullUser.emailVerifiedAt = new Date();
            fullUser.isVerified = true;
            await this.userRepository.save(fullUser);
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.EMAIL_VERIFIED, {
                user: fullUser,
                tenantId: fullUser.tenantId,
            });
            this.debugLogger.logFunctionExit('verifyEmail', 'AuthService');
            return { message: 'Email verified successfully' };
        }
        catch (error) {
            this.debugLogger.logError(error, 'verifyEmail');
            this.handleError(error, 'signup');
            throw error;
        }
    }
    async generateTokensPayload(session, otherPayload = {}) {
        let payload = {
            id: session.userId,
            sub: session.userId,
            sessionId: session.id,
            email: session.data?.user?.email,
            phone: session.data?.user?.phone,
            isVerified: session.data?.user?.isVerified,
            roles: session.data?.roles,
            tenantId: session.data?.user?.tenantId,
            isMfaEnabled: session.data?.user?.isMfaEnabled,
            isMfaVerified: session.data?.isMfaVerified,
            ...otherPayload,
        };
        const config = this.authConfigService.getConfig();
        if (config.session?.customizeTokenPayload) {
            payload = await config.session.customizeTokenPayload(payload, session);
        }
        return payload;
    }
    handleError(error, context) {
        const config = this.authConfigService.getConfig();
        if (config.errorHandler) {
            const result = config.errorHandler(error, context);
            if (result) {
                throw result;
            }
        }
    }
    async generateTokensFromSession(session) {
        const payload = await this.generateTokensPayload(session);
        const tokens = await this.jwtService.generateTokens(payload);
        return tokens;
    }
};
exports.AuthService = AuthService;
exports.AuthService = AuthService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(user_entity_1.NestAuthUser)),
    __param(1, (0, typeorm_1.InjectRepository)(otp_entity_1.NestAuthOTP)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.Repository,
        auth_provider_registry_service_1.AuthProviderRegistryService,
        mfa_service_1.MfaService,
        session_manager_service_1.SessionManagerService,
        jwt_service_1.JwtService,
        event_emitter_1.EventEmitter2,
        tenant_service_1.TenantService,
        debug_logger_service_1.DebugLoggerService,
        auth_config_service_1.AuthConfigService,
        user_service_1.UserService])
], AuthService);
//# sourceMappingURL=auth.service.js.map