"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.VerificationService = 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 event_emitter_1 = require("@nestjs/event-emitter");
const request_context_1 = require("../../request-context/request-context");
const debug_logger_service_1 = require("../../core/services/debug-logger.service");
const otp_flow_service_1 = require("./otp-flow.service");
const auth_config_service_1 = require("../../core/services/auth-config.service");
const email_verification_requested_event_1 = require("../events/email-verification-requested.event");
const phone_verification_requested_event_1 = require("../events/phone-verification-requested.event");
let VerificationService = class VerificationService {
    userRepository;
    eventEmitter;
    debugLogger;
    authConfigService;
    otpFlow;
    constructor(userRepository, eventEmitter, debugLogger, authConfigService, otpFlow) {
        this.userRepository = userRepository;
        this.eventEmitter = eventEmitter;
        this.debugLogger = debugLogger;
        this.authConfigService = authConfigService;
        this.otpFlow = otpFlow;
    }
    handleError(error, context) {
        const config = this.authConfigService.getConfig();
        if (config.errorHandler) {
            const result = config.errorHandler(error, context);
            if (result) {
                throw result;
            }
        }
    }
    async requireAuthenticatedUser() {
        const userId = request_context_1.RequestContext.currentUserId();
        if (!userId) {
            throw new common_1.UnauthorizedException({
                message: 'User not authenticated',
                code: auth_constants_1.ERROR_CODES.UNAUTHORIZED,
            });
        }
        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,
            });
        }
        return user;
    }
    async sendEmailVerification(_input) {
        this.debugLogger.logFunctionEntry('sendEmailVerification', 'VerificationService');
        try {
            const fullUser = await this.requireAuthenticatedUser();
            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 { entity: otpEntity, plainCode: code } = await this.otpFlow.createOtp({
                userId: fullUser.id,
                type: nest_auth_contracts_1.NestAuthOTPTypeEnum.EMAIL_VERIFICATION,
                replaceExisting: true,
            });
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.EMAIL_VERIFICATION_REQUESTED, new email_verification_requested_event_1.EmailVerificationRequestedEvent({
                user: fullUser,
                tenantId: request_context_1.RequestContext.currentTenantId(),
                otp: otpEntity,
                code,
            }));
            this.debugLogger.logFunctionExit('sendEmailVerification', 'VerificationService');
            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', 'VerificationService');
        try {
            const fullUser = await this.requireAuthenticatedUser();
            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,
                });
            }
            await this.otpFlow.validateAndConsume({
                userId: fullUser.id,
                type: nest_auth_contracts_1.NestAuthOTPTypeEnum.EMAIL_VERIFICATION,
                code: input.code,
            });
            fullUser.emailVerifiedAt = new Date();
            await this.userRepository.save(fullUser);
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.EMAIL_VERIFIED, {
                user: fullUser,
                tenantId: request_context_1.RequestContext.currentTenantId(),
            });
            this.debugLogger.logFunctionExit('verifyEmail', 'VerificationService');
            return { message: 'Email verified successfully' };
        }
        catch (error) {
            this.debugLogger.logError(error, 'verifyEmail');
            this.handleError(error, 'signup');
            throw error;
        }
    }
    async sendPhoneVerification(_input) {
        this.debugLogger.logFunctionEntry('sendPhoneVerification', 'VerificationService');
        try {
            const fullUser = await this.requireAuthenticatedUser();
            if (!fullUser.phone) {
                throw new common_1.BadRequestException({
                    message: 'User does not have a phone number',
                    code: auth_constants_1.ERROR_CODES.NO_PHONE_NUMBER,
                });
            }
            if (fullUser.phoneVerifiedAt) {
                throw new common_1.BadRequestException({
                    message: 'Phone number is already verified',
                    code: auth_constants_1.ERROR_CODES.PHONE_ALREADY_VERIFIED,
                });
            }
            const { entity: otpEntity, plainCode: code } = await this.otpFlow.createOtp({
                userId: fullUser.id,
                type: nest_auth_contracts_1.NestAuthOTPTypeEnum.PHONE_VERIFICATION,
                replaceExisting: true,
            });
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.PHONE_VERIFICATION_REQUESTED, new phone_verification_requested_event_1.PhoneVerificationRequestedEvent({
                user: fullUser,
                tenantId: request_context_1.RequestContext.currentTenantId(),
                otp: otpEntity,
                code,
            }));
            this.debugLogger.logFunctionExit('sendPhoneVerification', 'VerificationService');
            return { message: 'Verification SMS sent successfully' };
        }
        catch (error) {
            this.debugLogger.logError(error, 'sendPhoneVerification');
            this.handleError(error, 'signup');
            throw error;
        }
    }
    async verifyPhone(input) {
        this.debugLogger.logFunctionEntry('verifyPhone', 'VerificationService');
        try {
            const fullUser = await this.requireAuthenticatedUser();
            if (!fullUser.phone) {
                throw new common_1.BadRequestException({
                    message: 'User does not have a phone number',
                    code: auth_constants_1.ERROR_CODES.NO_PHONE_NUMBER,
                });
            }
            if (fullUser.phoneVerifiedAt) {
                throw new common_1.BadRequestException({
                    message: 'Phone number is already verified',
                    code: auth_constants_1.ERROR_CODES.PHONE_ALREADY_VERIFIED,
                });
            }
            await this.otpFlow.validateAndConsume({
                userId: fullUser.id,
                type: nest_auth_contracts_1.NestAuthOTPTypeEnum.PHONE_VERIFICATION,
                code: input.code,
            });
            fullUser.phoneVerifiedAt = new Date();
            await this.userRepository.save(fullUser);
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.PHONE_VERIFIED, {
                user: fullUser,
                tenantId: request_context_1.RequestContext.currentTenantId(),
            });
            this.debugLogger.logFunctionExit('verifyPhone', 'VerificationService');
            return { message: 'Phone verified successfully' };
        }
        catch (error) {
            this.debugLogger.logError(error, 'verifyPhone');
            this.handleError(error, 'signup');
            throw error;
        }
    }
};
exports.VerificationService = VerificationService;
exports.VerificationService = VerificationService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(user_entity_1.NestAuthUser)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        event_emitter_1.EventEmitter2,
        debug_logger_service_1.DebugLoggerService,
        auth_config_service_1.AuthConfigService,
        otp_flow_service_1.OtpFlowService])
], VerificationService);
//# sourceMappingURL=verification.service.js.map