"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); }
};
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 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 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 auth_config_service_1 = require("../../core/services/auth-config.service");
const otp_flow_service_1 = require("./otp-flow.service");
const has_token_1 = require("../../utils/has-token");
let PasswordService = class PasswordService {
    userRepository;
    authProviderRegistry;
    sessionManager;
    jwtService;
    eventEmitter;
    tenantService;
    debugLogger;
    authConfigService;
    otpFlow;
    constructor(userRepository, authProviderRegistry, sessionManager, jwtService, eventEmitter, tenantService, debugLogger, authConfigService, otpFlow) {
        this.userRepository = userRepository;
        this.authProviderRegistry = authProviderRegistry;
        this.sessionManager = sessionManager;
        this.jwtService = jwtService;
        this.eventEmitter = eventEmitter;
        this.tenantService = tenantService;
        this.debugLogger = debugLogger;
        this.authConfigService = authConfigService;
        this.otpFlow = otpFlow;
    }
    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;
            }
        }
    }
    resetSignature(passwordHash) {
        const secret = auth_config_service_1.AuthConfigService.getOptions().session?.jwt?.secret;
        if (!secret) {
            throw new Error('Missing session.jwt.secret');
        }
        return (0, has_token_1.hmacSha256Hex)(secret, passwordHash || '');
    }
    async changePassword(input) {
        this.debugLogger.logFunctionEntry('changePassword', 'PasswordService');
        try {
            const currentUser = await 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 },
                select: { id: true, email: true, phone: true, passwordHash: true },
            });
            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);
            user.mustChangePassword = false;
            await this.userRepository.save(user);
            await this.sessionManager.revokeAllUserSessions(user.id);
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.PASSWORD_CHANGED, new user_password_changed_event_1.UserPasswordChangedEvent({
                user,
                initiatedBy: 'user'
            }));
            return { message: 'Password changed successfully' };
        }
        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, tenantId ?? undefined);
            if (!identity) {
                return { message: 'If the account exists, a password reset code has been sent' };
            }
            const options = auth_config_service_1.AuthConfigService.getOptions();
            const { entity: otpEntity, plainCode } = await this.otpFlow.createOtp({
                userId: identity.user.id,
                type: nest_auth_contracts_1.NestAuthOTPTypeEnum.PASSWORD_RESET,
                otpOptions: options.otp,
                replaceExisting: true,
            });
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.PASSWORD_RESET_REQUESTED, new password_reset_requested_event_1.PasswordResetRequestedEvent({
                user: identity.user,
                tenantId,
                input,
                otp: otpEntity,
                code: plainCode,
                provider,
            }));
            this.debugLogger.logFunctionExit('forgotPassword', 'PasswordService');
            return { message: 'If the account exists, a password reset code has been sent' };
        }
        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, code, tenantId } = input;
            const resolvedTenantId = await this.tenantService.resolveTenantId(tenantId ?? null);
            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), resolvedTenantId ?? undefined);
            if (!identity) {
                throw new common_1.BadRequestException({
                    message: 'Invalid reset request',
                    code: auth_constants_1.ERROR_CODES.PASSWORD_RESET_INVALID_REQUEST,
                });
            }
            const userId = identity.user?.id;
            if (!userId) {
                throw new common_1.BadRequestException({
                    message: 'Invalid reset request',
                    code: auth_constants_1.ERROR_CODES.PASSWORD_RESET_INVALID_REQUEST,
                });
            }
            await this.otpFlow.validateAndConsume({
                userId,
                type: nest_auth_contracts_1.NestAuthOTPTypeEnum.PASSWORD_RESET,
                code,
            });
            const user = await this.userRepository.findOne({ where: { id: userId }, select: { id: true, passwordHash: true } });
            if (!user) {
                throw new common_1.BadRequestException({
                    message: 'User not found',
                    code: auth_constants_1.ERROR_CODES.USER_NOT_FOUND,
                });
            }
            const passwordHashPrefix = user.passwordHash ? this.resetSignature(user.passwordHash) : '';
            const resetToken = await this.jwtService.generatePasswordResetToken({
                userId: user.id,
                passwordHashPrefix,
                tenantId: resolvedTenantId,
                type: 'password-reset'
            });
            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 withHash = await this.userRepository.findOne({
                where: { id: decoded.userId },
                select: { id: true, passwordHash: true },
            });
            const currentSignature = withHash?.passwordHash ? this.resetSignature(withHash.passwordHash) : '';
            if (!(0, has_token_1.timingSafeEqualHex)(String(decoded.passwordHashPrefix || ''), currentSignature)) {
                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);
            user.mustChangePassword = false;
            await this.userRepository.save(user);
            await this.sessionManager.revokeAllUserSessions(user.id);
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.PASSWORD_RESET, new password_reset_event_1.PasswordResetEvent({
                user,
                tenantId: request_context_1.RequestContext.currentTenantId(),
                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)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        auth_provider_registry_service_1.AuthProviderRegistryService,
        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,
        otp_flow_service_1.OtpFlowService])
], PasswordService);
//# sourceMappingURL=password.service.js.map