"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.PasswordlessAuthProvider = 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 identity_entity_1 = require("../../user/entities/identity.entity");
const base_auth_provider_1 = require("./base-auth.provider");
const auth_constants_1 = require("../../auth.constants");
const utils_1 = require("../../utils");
const otp_entity_1 = require("../../auth/entities/otp.entity");
const nest_auth_contracts_1 = require("@ackplus/nest-auth-contracts");
let PasswordlessAuthProvider = class PasswordlessAuthProvider extends base_auth_provider_1.BaseAuthProvider {
    userRepository;
    authIdentityRepository;
    providerName = auth_constants_1.PASSWORDLESS_AUTH_PROVIDER;
    skipMfa = true;
    otpRepository;
    constructor(userRepository, authIdentityRepository) {
        super(userRepository, authIdentityRepository);
        this.userRepository = userRepository;
        this.authIdentityRepository = authIdentityRepository;
        this.enabled = this.options.passwordless?.enabled === true;
        this.otpRepository = otp_entity_1.NestAuthOTP.getRepository();
    }
    async validate(credentials, tenantId) {
        const identifier = credentials.identifier;
        const code = credentials.code;
        if (typeof identifier !== 'string' || typeof code !== 'string') {
            throw new common_1.BadRequestException({
                message: 'identifier and code are required for passwordless OTP login',
            });
        }
        for (const ch of credentials.channels) {
            const found = await this.findIdentityForChannel(ch, identifier, tenantId);
            if (!found?.identity.user) {
                continue;
            }
            const { identity, providerUserId } = found;
            const ok = await this.consumeOtp(identity.userId, nest_auth_contracts_1.NestAuthOTPTypeEnum.PASSWORDLESS_LOGIN, code);
            if (ok) {
                const user = identity.user;
                return {
                    userId: user.id,
                    email: user.email,
                    phone: user.phone,
                    emailVerified: ch === 'email',
                    phoneVerified: ch === 'sms',
                    metadata: user,
                };
            }
        }
        throw new common_1.BadRequestException({
            message: 'Invalid or expired code',
            code: auth_constants_1.ERROR_CODES.VERIFICATION_CODE_INVALID,
        });
    }
    async findIdentityForChannel(channel, identifier, tenantId) {
        if (channel === 'email') {
            const providerUserId = (0, utils_1.normalizedEmail)(identifier.trim());
            if (!providerUserId) {
                return null;
            }
            const identity = await this.authIdentityRepository.findOne({
                where: {
                    provider: auth_constants_1.EMAIL_AUTH_PROVIDER,
                    providerId: providerUserId,
                    ...(tenantId ? { user: { userAccesses: { tenantId: (0, typeorm_2.Equal)(tenantId) } } } : {}),
                },
                relations: ['user'],
            });
            return identity ? { identity, providerUserId } : null;
        }
        const providerUserId = (0, utils_1.normalizedPhone)(identifier.trim());
        if (!providerUserId) {
            return null;
        }
        const identity = await this.authIdentityRepository.findOne({
            where: {
                provider: auth_constants_1.PHONE_AUTH_PROVIDER,
                providerId: providerUserId,
                ...(tenantId ? { user: { userAccesses: { tenantId: (0, typeorm_2.Equal)(tenantId) } } } : {}),
            },
            relations: ['user'],
        });
        return identity ? { identity, providerUserId } : null;
    }
    async findIdentity(providerUserId, tenantId) {
        let found = await this.findIdentityForChannel('email', providerUserId, tenantId);
        if (found?.identity) {
            return found.identity;
        }
        found = await this.findIdentityForChannel('sms', providerUserId, tenantId);
        if (found?.identity) {
            return found.identity;
        }
        return null;
    }
    async findIdentityByUserId(userId) {
        return this.authIdentityRepository.findOne({
            where: { userId },
            relations: ['user'],
            order: { createdAt: 'ASC' },
        });
    }
    getRequiredFields() {
        return ['identifier', 'code', 'channels'];
    }
    async consumeOtp(userId, type, plainCode) {
        const candidates = await this.otpRepository.find({
            where: { userId, type },
            order: { createdAt: 'DESC' },
        });
        for (const otp of candidates) {
            if (await otp.validateCode(plainCode)) {
                await otp.remove();
                return true;
            }
        }
        return false;
    }
};
exports.PasswordlessAuthProvider = PasswordlessAuthProvider;
exports.PasswordlessAuthProvider = PasswordlessAuthProvider = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(user_entity_1.NestAuthUser)),
    __param(1, (0, typeorm_1.InjectRepository)(identity_entity_1.NestAuthIdentity)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.Repository])
], PasswordlessAuthProvider);
//# sourceMappingURL=passwordless-auth.provider.js.map