"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.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 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 event_emitter_1 = require("@nestjs/event-emitter");
const request_context_1 = require("../../request-context/request-context");
const otp_1 = require("../../utils/otp");
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");
let VerificationService = class VerificationService {
    userRepository;
    otpRepository;
    eventEmitter;
    debugLogger;
    authConfigService;
    constructor(userRepository, otpRepository, eventEmitter, debugLogger, authConfigService) {
        this.userRepository = userRepository;
        this.otpRepository = otpRepository;
        this.eventEmitter = eventEmitter;
        this.debugLogger = debugLogger;
        this.authConfigService = authConfigService;
    }
    handleError(error, context) {
        const config = this.authConfigService.getConfig();
        if (config.errorHandler) {
            const result = config.errorHandler(error, context);
            if (result) {
                throw result;
            }
        }
    }
    async sendEmailVerification(input) {
        this.debugLogger.logFunctionEntry('sendEmailVerification', 'VerificationService');
        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.userRepository.findOne({
                where: { id: user.id },
                relations: ['roles']
            });
            if (!fullUser) {
                throw new common_1.UnauthorizedException({
                    message: 'User not found',
                    code: auth_constants_1.ERROR_CODES.USER_NOT_FOUND,
                });
            }
            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: nest_auth_contracts_1.NestAuthOTPTypeEnum.VERIFICATION,
            });
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.EMAIL_VERIFICATION_REQUESTED, {
                user: fullUser,
                tenantId: fullUser.tenantId,
                otp: otpEntity,
            });
            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 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.userRepository.findOne({
                where: { id: user.id },
                relations: ['roles']
            });
            if (!fullUser) {
                throw new common_1.UnauthorizedException({
                    message: 'User not found',
                    code: auth_constants_1.ERROR_CODES.USER_NOT_FOUND,
                });
            }
            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: nest_auth_contracts_1.NestAuthOTPTypeEnum.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', 'VerificationService');
            return { message: 'Email verified successfully' };
        }
        catch (error) {
            this.debugLogger.logError(error, 'verifyEmail');
            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)),
    __param(1, (0, typeorm_1.InjectRepository)(otp_entity_1.NestAuthOTP)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.Repository,
        event_emitter_1.EventEmitter2,
        debug_logger_service_1.DebugLoggerService,
        auth_config_service_1.AuthConfigService])
], VerificationService);
//# sourceMappingURL=verification.service.js.map