"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.PasswordService = 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 nest_auth_contracts_1 = require("@ackplus/nest-auth-contracts");
const auth_constants_1 = require("../../auth.constants");
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_password_changed_event_1 = require("../events/user-password-changed.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 mfa_service_1 = require("./mfa.service");
const ms_1 = __importDefault(require("ms"));
let PasswordService = class PasswordService {
    userRepository;
    otpRepository;
    authProviderRegistry;
    mfaService;
    sessionManager;
    jwtService;
    eventEmitter;
    tenantService;
    debugLogger;
    authConfigService;
    constructor(userRepository, otpRepository, authProviderRegistry, mfaService, sessionManager, jwtService, eventEmitter, tenantService, debugLogger, authConfigService) {
        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;
    }
    get mfaConfig() {
        return auth_config_service_1.AuthConfigService.getOptions().mfa || {};
    }
    handleError(error, context) {
        const config = this.authConfigService.getConfig();
        if (config.errorHandler) {
            const result = config.errorHandler(error, context);
            if (result) {
                throw result;
            }
        }
    }
    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;
    }
    async generateTokensFromSession(session) {
        const payload = await this.generateTokensPayload(session);
        return this.jwtService.generateTokens(payload);
    }
    async generateAuthResponse(user, session, tokens, isRequiresMfa) {
        let response = {
            accessToken: tokens.accessToken,
            refreshToken: tokens.refreshToken,
            isRequiresMfa: isRequiresMfa,
        };
        if (isRequiresMfa) {
            const enabledMethods = await this.mfaService.getEnabledMethods(user.id);
            response.mfaMethods = enabledMethods;
            response.defaultMfaMethod = this.mfaService.mfaConfig?.defaultMethod || enabledMethods[0];
        }
        const config = this.authConfigService.getConfig();
        if (config.auth?.transformResponse) {
            response = await config.auth.transformResponse(response, user, session);
        }
        return response;
    }
    async changePassword(input) {
        this.debugLogger.logFunctionEntry('changePassword', 'PasswordService');
        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 },
                relations: ['roles']
            });
            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 session = await this.sessionManager.createSessionFromUser(user);
            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', 'PasswordService', { userId: user.id });
            return this.generateAuthResponse(user, session, tokens, isRequiresMfa);
        }
        catch (error) {
            this.debugLogger.logError(error, 'changePassword');
            this.handleError(error, 'password_change');
            throw error;
        }
    }
    async forgotPassword(input) {
        this.debugLogger.logFunctionEntry('forgotPassword', 'PasswordService', { 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) {
                const type = email ? 'Email' : 'Phone';
                throw new common_1.BadRequestException({
                    message: `${type} 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) {
                expiresAtMs = 900000;
            }
            await this.otpRepository.delete({
                userId: identity.user?.id,
                type: nest_auth_contracts_1.NestAuthOTPTypeEnum.PASSWORD_RESET
            });
            const otpEntity = await this.otpRepository.create({
                userId: identity.user?.id,
                type: nest_auth_contracts_1.NestAuthOTPTypeEnum.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', 'PasswordService');
            return true;
        }
        catch (error) {
            this.debugLogger.logError(error, 'forgotPassword');
            this.handleError(error, 'password_reset');
            throw error;
        }
    }
    async verifyForgotPasswordOtp(input) {
        this.debugLogger.logFunctionEntry('verifyForgotPasswordOtp', 'PasswordService');
        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: nest_auth_contracts_1.NestAuthOTPTypeEnum.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', 'PasswordService');
            return {
                message: 'OTP verified successfully',
                resetToken
            };
        }
        catch (error) {
            this.debugLogger.logError(error, 'verifyForgotPasswordOtp');
            this.handleError(error, 'password_reset');
            throw error;
        }
    }
    async resetPasswordWithToken(input) {
        this.debugLogger.logFunctionEntry('resetPasswordWithToken', 'PasswordService', { 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', 'PasswordService');
            return true;
        }
        catch (error) {
            this.debugLogger.logError(error, 'resetPasswordWithToken');
            this.handleError(error, 'password_reset');
            throw error;
        }
    }
};
exports.PasswordService = PasswordService;
exports.PasswordService = PasswordService = __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])
], PasswordService);
//# sourceMappingURL=password.service.js.map