"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.AdminRbacService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const role_entity_1 = require("../auth/entities/role.entity");
const permission_entity_1 = require("../auth/entities/permission.entity");
const role_permission_entity_1 = require("../auth/entities/role-permission.entity");
let AdminRbacService = class AdminRbacService {
    constructor(roleRepo, permRepo, rpRepo) {
        this.roleRepo = roleRepo;
        this.permRepo = permRepo;
        this.rpRepo = rpRepo;
    }
    async getRoles() {
        return this.roleRepo.find({
            where: { is_admin: true },
            relations: ["rolePermissions", "rolePermissions.permission"],
        });
    }
    async createRole(dto) {
        const exists = await this.roleRepo.findOne({ where: { name: dto.name } });
        if (exists)
            throw new common_1.ConflictException("El rol ya existe");
        return this.roleRepo.save(this.roleRepo.create({ name: dto.name, description: dto.description, is_admin: true }));
    }
    async deleteRole(id) {
        const role = await this.roleRepo.findOne({ where: { id } });
        if (!role)
            throw new common_1.NotFoundException("Rol no encontrado");
        if (role.name === "superadmin")
            throw new common_1.ConflictException("No se puede eliminar el rol superadmin");
        await this.roleRepo.remove(role);
        return { message: "Rol eliminado" };
    }
    async getPermissions() {
        return this.permRepo.find({ order: { module: "ASC", name: "ASC" } });
    }
    async createPermission(dto) {
        const exists = await this.permRepo.findOne({ where: { name: dto.name } });
        if (exists)
            throw new common_1.ConflictException("El permiso ya existe");
        return this.permRepo.save(this.permRepo.create(dto));
    }
    async deletePermission(id) {
        const perm = await this.permRepo.findOne({ where: { id } });
        if (!perm)
            throw new common_1.NotFoundException("Permiso no encontrado");
        await this.permRepo.remove(perm);
        return { message: "Permiso eliminado" };
    }
    async getRolePermissions(roleId) {
        return this.rpRepo.find({
            where: { role_id: roleId },
            relations: ["permission"],
        });
    }
    async assignPermission(roleId, permissionId) {
        const exists = await this.rpRepo.findOne({ where: { role_id: roleId, permission_id: permissionId } });
        if (exists)
            return exists;
        return this.rpRepo.save(this.rpRepo.create({ role_id: roleId, permission_id: permissionId }));
    }
    async revokePermission(rolePermissionId) {
        const rp = await this.rpRepo.findOne({ where: { id: rolePermissionId } });
        if (!rp)
            throw new common_1.NotFoundException("Asignación no encontrada");
        await this.rpRepo.remove(rp);
        return { message: "Permiso revocado" };
    }
    async seedDefaultPermissions() {
        const defaults = [
            { name: "banners.read", description: "Ver banners", module: "banners" },
            { name: "banners.write", description: "Crear/editar banners", module: "banners" },
            { name: "banners.delete", description: "Eliminar banners", module: "banners" },
            { name: "marquees.read", description: "Ver logos", module: "marquees" },
            { name: "marquees.write", description: "Crear/editar logos", module: "marquees" },
            { name: "marquees.delete", description: "Eliminar logos", module: "marquees" },
            { name: "testimonials.read", description: "Ver testimonios", module: "testimonials" },
            { name: "testimonials.write", description: "Crear/editar testimonios", module: "testimonials" },
            { name: "testimonials.delete", description: "Eliminar testimonios", module: "testimonials" },
            { name: "categories.read", description: "Ver categorías", module: "categories" },
            { name: "categories.write", description: "Crear/editar categorías", module: "categories" },
            { name: "categories.delete", description: "Eliminar categorías", module: "categories" },
            { name: "users.read", description: "Ver usuarios", module: "users" },
            { name: "users.write", description: "Crear/editar usuarios", module: "users" },
            { name: "users.delete", description: "Eliminar usuarios", module: "users" },
            { name: "plans.read", description: "Ver planes", module: "plans" },
            { name: "plans.write", description: "Crear/editar planes", module: "plans" },
            { name: "plans.delete", description: "Eliminar planes", module: "plans" },
            { name: "settings.read", description: "Ver configuración", module: "settings" },
            { name: "settings.write", description: "Editar configuración", module: "settings" },
            { name: "backing.read", description: "Ver logos respaldo", module: "backing" },
            { name: "backing.write", description: "Crear/editar logos respaldo", module: "backing" },
            { name: "backing.delete", description: "Eliminar logos respaldo", module: "backing" },
            { name: "secondary_banners.read", description: "Ver banners promo", module: "secondary_banners" },
            { name: "secondary_banners.write", description: "Crear/editar banners promo", module: "secondary_banners" },
            { name: "secondary_banners.delete", description: "Eliminar banners promo", module: "secondary_banners" },
            { name: "rbac.read", description: "Ver roles y permisos", module: "rbac" },
            { name: "rbac.write", description: "Gestionar roles y permisos", module: "rbac" },
        ];
        let created = 0;
        for (const d of defaults) {
            const exists = await this.permRepo.findOne({ where: { name: d.name } });
            if (!exists) {
                await this.permRepo.save(this.permRepo.create(d));
                created++;
            }
        }
        const superadmin = await this.roleRepo.findOne({ where: { name: "superadmin" } });
        if (superadmin) {
            if (!superadmin.is_admin) {
                await this.roleRepo.update(superadmin.id, { is_admin: true });
            }
            const allPerms = await this.permRepo.find();
            for (const perm of allPerms) {
                const exists = await this.rpRepo.findOne({ where: { role_id: superadmin.id, permission_id: perm.id } });
                if (!exists) {
                    await this.rpRepo.save(this.rpRepo.create({ role_id: superadmin.id, permission_id: perm.id }));
                }
            }
        }
        return { message: `Creados ${created} permisos. Superadmin actualizado.` };
    }
};
exports.AdminRbacService = AdminRbacService;
exports.AdminRbacService = AdminRbacService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(role_entity_1.Role)),
    __param(1, (0, typeorm_1.InjectRepository)(permission_entity_1.Permission)),
    __param(2, (0, typeorm_1.InjectRepository)(role_permission_entity_1.RolePermission)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository])
], AdminRbacService);
//# sourceMappingURL=admin-rbac.service.js.map