"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 NestAuthUserAccess_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NestAuthUserAccess = void 0;
const typeorm_1 = require("typeorm");
const tenant_entity_1 = require("../../tenant/entities/tenant.entity");
const user_entity_1 = require("./user.entity");
const role_entity_1 = require("../../role/entities/role.entity");
const lodash_1 = require("lodash");
const role_mapper_util_1 = require("../../role/utils/role-mapper.util");
let NestAuthUserAccess = NestAuthUserAccess_1 = class NestAuthUserAccess extends typeorm_1.BaseEntity {
    id;
    userId;
    tenantId;
    user;
    tenant;
    roles;
    isActive;
    isDefault;
    status;
    metadata;
    createdAt;
    updatedAt;
    async getPermissions(tenantId) {
        const roles = await this.getRoles(tenantId, true);
        return (0, lodash_1.chain)(roles)
            .map((role) => (0, role_mapper_util_1.getRolePermissionNames)(role))
            .flatten()
            .uniq()
            .value();
    }
    async getRoles(tenantId, withPermissions = false) {
        const access = await NestAuthUserAccess_1.findOne({
            where: { userId: this.userId, tenantId: tenantId ? (0, typeorm_1.Equal)(tenantId) : (0, typeorm_1.IsNull)() },
            relations: ['roles', ...(withPermissions ? ['roles.rolePermissions', 'roles.rolePermissions.permission'] : [])],
        });
        return access?.roles?.length ? access.roles : [];
    }
    async assignRoles(roleIds, manager) {
        const ids = Array.isArray(roleIds) ? roleIds : [roleIds];
        const roleRepo = manager
            ? manager.getRepository(role_entity_1.NestAuthRole)
            : role_entity_1.NestAuthRole.getRepository();
        const accessRepo = manager
            ? manager.getRepository(NestAuthUserAccess_1)
            : NestAuthUserAccess_1.getRepository();
        this.roles = ids.length
            ? await roleRepo.find({ where: { id: (0, typeorm_1.In)(ids) } })
            : [];
        await accessRepo.save(this);
    }
};
exports.NestAuthUserAccess = NestAuthUserAccess;
__decorate([
    (0, typeorm_1.PrimaryGeneratedColumn)('uuid'),
    __metadata("design:type", String)
], NestAuthUserAccess.prototype, "id", void 0);
__decorate([
    (0, typeorm_1.Column)({ nullable: false }),
    (0, typeorm_1.Index)(),
    (0, typeorm_1.RelationId)((access) => access.user),
    __metadata("design:type", String)
], NestAuthUserAccess.prototype, "userId", void 0);
__decorate([
    (0, typeorm_1.Column)({ nullable: true }),
    (0, typeorm_1.Index)(),
    (0, typeorm_1.RelationId)((access) => access.tenant),
    __metadata("design:type", String)
], NestAuthUserAccess.prototype, "tenantId", void 0);
__decorate([
    (0, typeorm_1.ManyToOne)(() => user_entity_1.NestAuthUser, { onDelete: 'CASCADE' }),
    __metadata("design:type", user_entity_1.NestAuthUser)
], NestAuthUserAccess.prototype, "user", void 0);
__decorate([
    (0, typeorm_1.ManyToOne)(() => tenant_entity_1.NestAuthTenant, { onDelete: 'CASCADE', nullable: true }),
    __metadata("design:type", tenant_entity_1.NestAuthTenant)
], NestAuthUserAccess.prototype, "tenant", void 0);
__decorate([
    (0, typeorm_1.ManyToMany)(() => role_entity_1.NestAuthRole, role => role.userAccesses, { onDelete: 'CASCADE' }),
    (0, typeorm_1.JoinTable)({
        name: 'nest_auth_user_access_roles',
        joinColumn: { name: 'nestAuthUserAccessId', referencedColumnName: 'id' },
        inverseJoinColumn: { name: 'nestAuthRolesId', referencedColumnName: 'id' },
    }),
    __metadata("design:type", Array)
], NestAuthUserAccess.prototype, "roles", void 0);
__decorate([
    (0, typeorm_1.Column)({ default: true }),
    __metadata("design:type", Boolean)
], NestAuthUserAccess.prototype, "isActive", void 0);
__decorate([
    (0, typeorm_1.Column)({ default: false }),
    __metadata("design:type", Boolean)
], NestAuthUserAccess.prototype, "isDefault", void 0);
__decorate([
    (0, typeorm_1.Column)({ default: 'active' }),
    __metadata("design:type", String)
], NestAuthUserAccess.prototype, "status", void 0);
__decorate([
    (0, typeorm_1.Column)({ type: 'simple-json', nullable: true, default: '{}' }),
    __metadata("design:type", Object)
], NestAuthUserAccess.prototype, "metadata", void 0);
__decorate([
    (0, typeorm_1.CreateDateColumn)(),
    __metadata("design:type", Date)
], NestAuthUserAccess.prototype, "createdAt", void 0);
__decorate([
    (0, typeorm_1.UpdateDateColumn)(),
    __metadata("design:type", Date)
], NestAuthUserAccess.prototype, "updatedAt", void 0);
exports.NestAuthUserAccess = NestAuthUserAccess = NestAuthUserAccess_1 = __decorate([
    (0, typeorm_1.Entity)('nest_auth_user_accesses'),
    (0, typeorm_1.Index)('UQ_user_tenant_not_null', ['userId', 'tenantId'], {
        unique: true,
        where: `"tenantId" IS NOT NULL`,
    }),
    (0, typeorm_1.Index)('UQ_user_null_tenant', ['userId'], {
        unique: true,
        where: `"tenantId" IS NULL`,
    })
], NestAuthUserAccess);
//# sourceMappingURL=user-access.entity.js.map