"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 NestAuthRole_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NestAuthRole = void 0;
const typeorm_1 = require("typeorm");
const lodash_1 = require("lodash");
const auth_constants_1 = require("../../auth.constants");
const tenant_entity_1 = require("../../tenant/entities/tenant.entity");
const common_1 = require("@nestjs/common");
const user_entity_1 = require("../../user/entities/user.entity");
let NestAuthRole = NestAuthRole_1 = class NestAuthRole extends typeorm_1.BaseEntity {
    id;
    name;
    guard;
    tenantId;
    tenant;
    isSystem;
    isActive;
    permissions;
    createdAt;
    updatedAt;
    users;
    static async createRole(name, guard = auth_constants_1.DEFAULT_GUARD_NAME, isSystem = false, tenantId) {
        const existingSystemRole = await NestAuthRole_1.findOne({
            where: { name, isSystem: true }
        });
        if (existingSystemRole) {
            throw new common_1.ConflictException(`Cannot create role with name '${name}' as it conflicts with a system role`);
        }
        if (!isSystem && !tenantId) {
            throw new common_1.BadRequestException('Tenant ID is required');
        }
        const role = new NestAuthRole_1();
        role.name = name;
        role.guard = guard;
        role.isSystem = isSystem;
        role.tenantId = isSystem ? null : tenantId;
        await role.save();
        return role;
    }
    async syncPermissions(permissions) {
        const newPermissions = Array.isArray(permissions) ? permissions : [permissions];
        this.permissions = newPermissions;
    }
    async removePermissions(permissions) {
        const removingPermissions = Array.isArray(permissions) ? permissions : [permissions];
        this.permissions = this.permissions.filter(permission => !removingPermissions.includes(permission));
    }
    async attachPermissions(permissions) {
        const existingPermissions = this.permissions;
        const newPermissions = Array.isArray(permissions) ? permissions : [permissions];
        this.permissions = (0, lodash_1.uniq)([...existingPermissions, ...newPermissions]);
    }
};
exports.NestAuthRole = NestAuthRole;
__decorate([
    (0, typeorm_1.PrimaryGeneratedColumn)('uuid'),
    __metadata("design:type", String)
], NestAuthRole.prototype, "id", void 0);
__decorate([
    (0, typeorm_1.Column)(),
    __metadata("design:type", String)
], NestAuthRole.prototype, "name", void 0);
__decorate([
    (0, typeorm_1.Column)({ nullable: true, default: auth_constants_1.DEFAULT_GUARD_NAME }),
    __metadata("design:type", String)
], NestAuthRole.prototype, "guard", void 0);
__decorate([
    (0, typeorm_1.Column)({ nullable: true }),
    (0, typeorm_1.RelationId)((role) => role.tenant),
    __metadata("design:type", String)
], NestAuthRole.prototype, "tenantId", void 0);
__decorate([
    (0, typeorm_1.ManyToOne)(() => tenant_entity_1.NestAuthTenant, { onDelete: 'CASCADE' }),
    __metadata("design:type", tenant_entity_1.NestAuthTenant)
], NestAuthRole.prototype, "tenant", void 0);
__decorate([
    (0, typeorm_1.Column)({ default: false }),
    __metadata("design:type", Boolean)
], NestAuthRole.prototype, "isSystem", void 0);
__decorate([
    (0, typeorm_1.Column)({ default: true }),
    __metadata("design:type", Boolean)
], NestAuthRole.prototype, "isActive", void 0);
__decorate([
    (0, typeorm_1.Column)({
        type: 'simple-json',
        nullable: true,
        default: '{}'
    }),
    __metadata("design:type", Array)
], NestAuthRole.prototype, "permissions", void 0);
__decorate([
    (0, typeorm_1.CreateDateColumn)(),
    __metadata("design:type", Date)
], NestAuthRole.prototype, "createdAt", void 0);
__decorate([
    (0, typeorm_1.UpdateDateColumn)(),
    __metadata("design:type", Date)
], NestAuthRole.prototype, "updatedAt", void 0);
__decorate([
    (0, typeorm_1.ManyToMany)(() => user_entity_1.NestAuthUser, user => user.roles, { onDelete: 'CASCADE' }),
    (0, typeorm_1.JoinTable)({
        name: 'nest_auth_role_nest_auth_users',
        joinColumn: {
            name: 'nestAuthRolesId',
            referencedColumnName: 'id',
        },
        inverseJoinColumn: {
            name: 'nestAuthUsersId',
            referencedColumnName: 'id',
        },
    }),
    __metadata("design:type", Array)
], NestAuthRole.prototype, "users", void 0);
exports.NestAuthRole = NestAuthRole = NestAuthRole_1 = __decorate([
    (0, typeorm_1.Entity)('nest_auth_roles'),
    (0, typeorm_1.Unique)(['name', 'guard', 'tenantId'])
], NestAuthRole);
//# sourceMappingURL=role.entity.js.map