"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
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 __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var NestAuthUser_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NestAuthUser = void 0;
const typeorm_1 = require("typeorm");
const auth_config_service_1 = require("../../core/services/auth-config.service");
const tenant_entity_1 = require("../../tenant/entities/tenant.entity");
const identity_entity_1 = require("./identity.entity");
const session_entity_1 = require("../../session/entities/session.entity");
const lodash_1 = require("lodash");
const otp_entity_1 = require("../../auth/entities/otp.entity");
const mfa_secret_entity_1 = require("../../auth/entities/mfa-secret.entity");
const role_entity_1 = require("../../role/entities/role.entity");
let NestAuthUser = class NestAuthUser extends typeorm_1.BaseEntity {
    static { NestAuthUser_1 = this; }
    id;
    email;
    emailVerifiedAt;
    phone;
    phoneVerifiedAt;
    passwordHash;
    isVerified;
    isActive;
    metadata;
    tenantId;
    isMfaEnabled;
    mfaRecoveryCode;
    tenant;
    identities;
    mfaSecrets;
    sessions;
    otps;
    roles;
    emailTenant;
    phoneTenant;
    createdAt;
    updatedAt;
    static argon2Loader = null;
    static async getArgon2() {
        if (!NestAuthUser_1.argon2Loader) {
            NestAuthUser_1.argon2Loader = Promise.resolve().then(() => __importStar(require('argon2'))).catch((error) => {
                throw new Error(`argon2 native module is not available. ` +
                    `Install/build argon2 before using password hashing. ` +
                    `Original error: ${error?.message ?? error}`);
            });
        }
        return NestAuthUser_1.argon2Loader;
    }
    updateTenantFields() {
        if (this.email) {
            this.email = this.email.toLowerCase().trim();
        }
        this.emailTenant = this.email ? `${this.email}:${this.tenantId || 'global'}` : null;
        this.phoneTenant = this.phone ? `${this.phone}:${this.tenantId || 'global'}` : null;
    }
    async getPermissions() {
        if (!this.roles) {
            this.roles = await role_entity_1.NestAuthRole.find({
                select: {
                    id: true,
                    name: true,
                    permissions: true
                },
                where: { users: { id: this.id }, tenantId: this.tenantId }
            });
        }
        return (0, lodash_1.chain)(this.roles)
            .map(role => role.permissions)
            .flatten()
            .uniq()
            .value();
    }
    async getRoles() {
        if (!this.roles) {
            this.roles = await role_entity_1.NestAuthRole.find({
                select: {
                    id: true,
                    name: true,
                    isSystem: true,
                    guard: true,
                },
                where: { users: { id: this.id }, tenantId: this.tenantId }
            });
        }
        return this.roles;
    }
    async assignRoles(roles, guard) {
        this.roles = await role_entity_1.NestAuthRole.find({
            where: [
                { name: (0, typeorm_1.In)(Array.isArray(roles) ? roles : [roles]), isSystem: true, guard },
                { name: (0, typeorm_1.In)(Array.isArray(roles) ? roles : [roles]), tenantId: this.tenantId, isSystem: false, guard }
            ]
        });
    }
    async findOrCreateIdentity(provider, providerId) {
        const existingIdentity = await identity_entity_1.NestAuthIdentity.findOne({
            where: { provider, providerId, userId: this.id }
        });
        if (existingIdentity) {
            return existingIdentity;
        }
        const identity = new identity_entity_1.NestAuthIdentity();
        identity.provider = provider;
        identity.providerId = providerId;
        identity.user = this;
        return identity.save();
    }
    async updateOrCreateIdentity(provider, data) {
        let identity = {};
        if (provider) {
            identity = await identity_entity_1.NestAuthIdentity.findOne({
                where: { provider, userId: this.id },
            });
        }
        identity = identity_entity_1.NestAuthIdentity.create({
            provider,
            ...identity,
            ...data,
            userId: this.id,
        });
        return identity.save();
    }
    async validatePassword(password) {
        if (!this.passwordHash)
            return false;
        const options = auth_config_service_1.AuthConfigService.getOptions();
        if (options.password?.verify) {
            return await options.password.verify(password, this.passwordHash);
        }
        try {
            const argon2 = await NestAuthUser_1.getArgon2();
            return await argon2.verify(this.passwordHash, password);
        }
        catch (error) {
            return false;
        }
    }
    async setPassword(password) {
        const options = auth_config_service_1.AuthConfigService.getOptions();
        if (options.password?.validate) {
            const isValid = await options.password.validate(password);
            if (!isValid) {
                throw new Error('Password does not meet requirements');
            }
        }
        if (options.password?.hash) {
            this.passwordHash = await options.password.hash(password);
            return;
        }
        const argon2 = await NestAuthUser_1.getArgon2();
        this.passwordHash = await argon2.hash(password, {
            type: argon2.argon2id,
            memoryCost: 65536,
            timeCost: 3,
            parallelism: 4
        });
    }
};
exports.NestAuthUser = NestAuthUser;
__decorate([
    (0, typeorm_1.PrimaryGeneratedColumn)('uuid'),
    __metadata("design:type", String)
], NestAuthUser.prototype, "id", void 0);
__decorate([
    (0, typeorm_1.Column)({ nullable: true }),
    (0, typeorm_1.Index)(),
    __metadata("design:type", String)
], NestAuthUser.prototype, "email", void 0);
__decorate([
    (0, typeorm_1.Column)({ nullable: true }),
    (0, typeorm_1.Index)(),
    __metadata("design:type", Date)
], NestAuthUser.prototype, "emailVerifiedAt", void 0);
__decorate([
    (0, typeorm_1.Column)({ nullable: true }),
    (0, typeorm_1.Index)(),
    __metadata("design:type", String)
], NestAuthUser.prototype, "phone", void 0);
__decorate([
    (0, typeorm_1.Column)({ nullable: true }),
    (0, typeorm_1.Index)(),
    __metadata("design:type", Date)
], NestAuthUser.prototype, "phoneVerifiedAt", void 0);
__decorate([
    (0, typeorm_1.Column)({ nullable: true }),
    __metadata("design:type", String)
], NestAuthUser.prototype, "passwordHash", void 0);
__decorate([
    (0, typeorm_1.Column)({ default: false }),
    __metadata("design:type", Boolean)
], NestAuthUser.prototype, "isVerified", void 0);
__decorate([
    (0, typeorm_1.Column)({ default: true }),
    __metadata("design:type", Boolean)
], NestAuthUser.prototype, "isActive", void 0);
__decorate([
    (0, typeorm_1.Column)({ type: 'simple-json', nullable: true, default: '{}' }),
    __metadata("design:type", Object)
], NestAuthUser.prototype, "metadata", void 0);
__decorate([
    (0, typeorm_1.Column)({ nullable: true }),
    __metadata("design:type", String)
], NestAuthUser.prototype, "tenantId", void 0);
__decorate([
    (0, typeorm_1.Column)({ default: false }),
    __metadata("design:type", Boolean)
], NestAuthUser.prototype, "isMfaEnabled", void 0);
__decorate([
    (0, typeorm_1.Column)({ nullable: true }),
    __metadata("design:type", String)
], NestAuthUser.prototype, "mfaRecoveryCode", void 0);
__decorate([
    (0, typeorm_1.ManyToOne)(() => tenant_entity_1.NestAuthTenant, { onDelete: 'CASCADE' }),
    __metadata("design:type", tenant_entity_1.NestAuthTenant)
], NestAuthUser.prototype, "tenant", void 0);
__decorate([
    (0, typeorm_1.OneToMany)(() => identity_entity_1.NestAuthIdentity, identity => identity.user),
    __metadata("design:type", Array)
], NestAuthUser.prototype, "identities", void 0);
__decorate([
    (0, typeorm_1.OneToMany)(() => mfa_secret_entity_1.NestAuthMFASecret, mfaSecret => mfaSecret.user),
    __metadata("design:type", Array)
], NestAuthUser.prototype, "mfaSecrets", void 0);
__decorate([
    (0, typeorm_1.OneToMany)(() => session_entity_1.NestAuthSession, session => session.user),
    __metadata("design:type", Array)
], NestAuthUser.prototype, "sessions", void 0);
__decorate([
    (0, typeorm_1.OneToMany)(() => otp_entity_1.NestAuthOTP, otp => otp.user),
    __metadata("design:type", Array)
], NestAuthUser.prototype, "otps", void 0);
__decorate([
    (0, typeorm_1.ManyToMany)(() => role_entity_1.NestAuthRole, role => role.users, { onDelete: 'CASCADE' }),
    __metadata("design:type", Array)
], NestAuthUser.prototype, "roles", void 0);
__decorate([
    (0, typeorm_1.Index)('IDX_USER_EMAIL_TENANT', { unique: true }),
    (0, typeorm_1.Column)({ nullable: true }),
    __metadata("design:type", String)
], NestAuthUser.prototype, "emailTenant", void 0);
__decorate([
    (0, typeorm_1.Index)('IDX_USER_PHONE_TENANT', { unique: true }),
    (0, typeorm_1.Column)({ nullable: true }),
    __metadata("design:type", String)
], NestAuthUser.prototype, "phoneTenant", void 0);
__decorate([
    (0, typeorm_1.CreateDateColumn)(),
    __metadata("design:type", Date)
], NestAuthUser.prototype, "createdAt", void 0);
__decorate([
    (0, typeorm_1.UpdateDateColumn)(),
    __metadata("design:type", Date)
], NestAuthUser.prototype, "updatedAt", void 0);
__decorate([
    (0, typeorm_1.BeforeInsert)(),
    (0, typeorm_1.BeforeUpdate)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], NestAuthUser.prototype, "updateTenantFields", null);
exports.NestAuthUser = NestAuthUser = NestAuthUser_1 = __decorate([
    (0, typeorm_1.Entity)('nest_auth_users')
], NestAuthUser);
//# sourceMappingURL=user.entity.js.map