"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.AdminPermissionsController = void 0;
const common_1 = require("@nestjs/common");
const common_2 = require("@nestjs/common");
const admin_session_guard_1 = require("../guards/admin-session.guard");
const admin_permission_dto_1 = require("../dto/admin-permission.dto");
const permission_service_1 = require("../../permission/services/permission.service");
const role_service_1 = require("../../role/services/role.service");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const role_entity_1 = require("../../role/entities/role.entity");
let AdminPermissionsController = class AdminPermissionsController {
    permissionService;
    roleService;
    roleRepository;
    constructor(permissionService, roleService, roleRepository) {
        this.permissionService = permissionService;
        this.roleService = roleService;
        this.roleRepository = roleRepository;
    }
    async listPermissions(search, category, guard, limit) {
        const limitNum = limit ? parseInt(limit, 10) : undefined;
        const permissions = await this.permissionService.getPermissions({
            search,
            category,
            guard,
            limit: limitNum,
        });
        return {
            data: permissions.map((p) => this.toSafePermission(p)),
        };
    }
    async getGuards() {
        const guards = await this.permissionService.getGuards();
        return { data: guards };
    }
    async searchPermissions(query, guard, limit) {
        if (!query || query.trim().length === 0) {
            return { data: [] };
        }
        const limitNum = limit ? parseInt(limit, 10) : 20;
        const permissions = await this.permissionService.searchPermissions(query.trim(), guard, limitNum);
        return {
            data: permissions.map((p) => this.toSafePermission(p)),
        };
    }
    async getCategories() {
        const categories = await this.permissionService.getCategories();
        return { data: categories };
    }
    async createPermission(dto) {
        const permission = await this.permissionService.createPermission({
            name: dto.name,
            guard: dto.guard,
            description: dto.description,
            category: dto.category,
            metadata: dto.metadata,
        });
        return {
            permission: this.toSafePermission(permission),
        };
    }
    async getPermission(id) {
        try {
            const permission = await this.permissionService.getPermissionById(id);
            return {
                permission: this.toSafePermission(permission),
            };
        }
        catch (error) {
            if (error instanceof common_2.NotFoundException) {
                throw error;
            }
            throw new common_2.NotFoundException('Permission not found');
        }
    }
    async updatePermission(id, dto) {
        const oldPermission = await this.permissionService.getPermissionById(id);
        const oldName = oldPermission.name;
        const oldGuard = oldPermission.guard;
        const permission = await this.permissionService.updatePermission(id, {
            name: dto.name,
            guard: dto.guard,
            description: dto.description,
            category: dto.category,
            metadata: dto.metadata,
        });
        if (dto.name && dto.name !== oldName && dto.updateInRoles === true) {
            await this.updatePermissionInRoles(oldName, oldGuard, dto.name);
        }
        return {
            permission: this.toSafePermission(permission),
        };
    }
    async updatePermissionInRoles(oldPermissionName, guard, newPermissionName) {
        const roles = await this.roleRepository.find({
            where: { guard },
        });
        for (const role of roles) {
            if (role.permissions && role.permissions.includes(oldPermissionName)) {
                role.permissions = role.permissions.map((perm) => (perm === oldPermissionName ? newPermissionName : perm));
                await this.roleRepository.save(role);
            }
        }
    }
    async deletePermission(id) {
        await this.permissionService.deletePermission(id);
        return { message: 'Permission deleted successfully' };
    }
    toSafePermission(permission) {
        return {
            id: permission.id,
            name: permission.name,
            guard: permission.guard,
            description: permission.description,
            category: permission.category,
            metadata: permission.metadata || {},
            createdAt: permission.createdAt,
            updatedAt: permission.updatedAt,
        };
    }
};
exports.AdminPermissionsController = AdminPermissionsController;
__decorate([
    (0, common_1.Get)(),
    __param(0, (0, common_1.Query)('search')),
    __param(1, (0, common_1.Query)('category')),
    __param(2, (0, common_1.Query)('guard')),
    __param(3, (0, common_1.Query)('limit')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String, String]),
    __metadata("design:returntype", Promise)
], AdminPermissionsController.prototype, "listPermissions", null);
__decorate([
    (0, common_1.Get)('guards'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], AdminPermissionsController.prototype, "getGuards", null);
__decorate([
    (0, common_1.Get)('search'),
    __param(0, (0, common_1.Query)('q')),
    __param(1, (0, common_1.Query)('guard')),
    __param(2, (0, common_1.Query)('limit')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String]),
    __metadata("design:returntype", Promise)
], AdminPermissionsController.prototype, "searchPermissions", null);
__decorate([
    (0, common_1.Get)('categories'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], AdminPermissionsController.prototype, "getCategories", null);
__decorate([
    (0, common_1.Post)(),
    __param(0, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [admin_permission_dto_1.AdminCreatePermissionDto]),
    __metadata("design:returntype", Promise)
], AdminPermissionsController.prototype, "createPermission", null);
__decorate([
    (0, common_1.Get)(':id'),
    __param(0, (0, common_1.Param)('id')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], AdminPermissionsController.prototype, "getPermission", null);
__decorate([
    (0, common_1.Patch)(':id'),
    __param(0, (0, common_1.Param)('id')),
    __param(1, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, admin_permission_dto_1.AdminUpdatePermissionDto]),
    __metadata("design:returntype", Promise)
], AdminPermissionsController.prototype, "updatePermission", null);
__decorate([
    (0, common_1.Delete)(':id'),
    __param(0, (0, common_1.Param)('id')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], AdminPermissionsController.prototype, "deletePermission", null);
exports.AdminPermissionsController = AdminPermissionsController = __decorate([
    (0, common_1.Controller)('auth/admin/api/permissions'),
    (0, common_1.UseGuards)(admin_session_guard_1.AdminSessionGuard),
    __param(2, (0, typeorm_1.InjectRepository)(role_entity_1.NestAuthRole)),
    __metadata("design:paramtypes", [permission_service_1.PermissionService,
        role_service_1.RoleService,
        typeorm_2.Repository])
], AdminPermissionsController);
//# sourceMappingURL=admin-permissions.controller.js.map