"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.OtpFlowService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const otp_entity_1 = require("../entities/otp.entity");
const otp_1 = require("../../utils/otp");
const auth_config_service_1 = require("../../core/services/auth-config.service");
const auth_constants_1 = require("../../auth.constants");
const ms_1 = __importDefault(require("ms"));
let OtpFlowService = class OtpFlowService {
    otpRepository;
    constructor(otpRepository) {
        this.otpRepository = otpRepository;
    }
    get otpConfig() {
        return auth_config_service_1.AuthConfigService.getOptions().otp;
    }
    resolveExpiresMs(raw, fallbackMsString) {
        const fallback = (0, ms_1.default)(fallbackMsString);
        if (raw === undefined || raw === null) {
            return fallback;
        }
        let n;
        if (typeof raw === 'string') {
            const parsed = (0, ms_1.default)(raw);
            n = typeof parsed === 'number' ? parsed : fallback;
        }
        else {
            n = raw;
        }
        if (typeof n !== 'number' || !Number.isFinite(n) || n <= 0) {
            return fallback;
        }
        return n;
    }
    async generatePlainCode(otpOptions) {
        const length = otpOptions?.length ?? 6;
        const format = otpOptions?.format ?? 'numeric';
        if (otpOptions?.generate) {
            const out = otpOptions.generate(length, format);
            return out instanceof Promise ? out : Promise.resolve(out);
        }
        return (0, otp_1.generateOtp)(length, format);
    }
    async deleteByUserAndType(userId, type) {
        await this.otpRepository.delete({ userId, type });
    }
    async createOtp(params) {
        const { userId, type, otpOptions, replaceExisting = true } = params;
        if (replaceExisting) {
            await this.deleteByUserAndType(userId, type);
        }
        const expiresAtMs = this.resolveExpiresMs(this.otpConfig.codeExpiresIn, '10m');
        const expiresAt = new Date(Date.now() + expiresAtMs);
        const entity = this.otpRepository.create({
            userId,
            type,
            expiresAt,
        });
        const plainCode = await this.generatePlainCode(otpOptions ?? undefined);
        await entity.setCode(plainCode);
        await this.otpRepository.save(entity);
        return { entity, plainCode };
    }
    async validateAndConsume(params) {
        const { userId, type, code } = params;
        const trimmed = code?.trim();
        if (!trimmed) {
            throw new common_1.BadRequestException({
                message: 'Verification code is required',
                code: auth_constants_1.ERROR_CODES.MISSING_REQUIRED_FIELD,
            });
        }
        const candidates = await this.otpRepository.find({
            where: { userId, type },
            order: { createdAt: 'DESC' },
        });
        for (const row of candidates) {
            const otp = await this.otpRepository.findOne({ where: { id: row.id } });
            if (!otp) {
                continue;
            }
            const expired = otp.expiresAt.getTime() <= Date.now();
            const matches = await otp.validateCode(trimmed);
            if (!matches) {
                continue;
            }
            if (expired) {
                throw new common_1.BadRequestException({
                    message: 'Verification code has expired',
                    code: auth_constants_1.ERROR_CODES.VERIFICATION_CODE_EXPIRED,
                });
            }
            await this.otpRepository.remove(otp);
            return;
        }
        throw new common_1.BadRequestException({
            message: 'Invalid verification code',
            code: auth_constants_1.ERROR_CODES.VERIFICATION_CODE_INVALID,
        });
    }
};
exports.OtpFlowService = OtpFlowService;
exports.OtpFlowService = OtpFlowService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(otp_entity_1.NestAuthOTP)),
    __metadata("design:paramtypes", [typeorm_2.Repository])
], OtpFlowService);
//# sourceMappingURL=otp-flow.service.js.map