"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); }
};
var PermissionMetadataService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PermissionMetadataService = void 0;
const common_1 = require("@nestjs/common");
const cache_manager_1 = require("@nestjs/cache-manager");
const core_1 = require("@nestjs/core");
const typeorm_1 = require("@nestjs/typeorm");
const crud_service_1 = require("./crud.service");
const cache_helper_1 = require("../helpers/cache.helper");
const typeorm_2 = require("typeorm");
const permission_metadata_repository_1 = require("../repository/permission-metadata.repository");
let PermissionMetadataService = PermissionMetadataService_1 = class PermissionMetadataService extends crud_service_1.CRUDService {
    constructor(entityManager, repo, moduleRef, cacheManager) {
        super(entityManager, repo, 'permissionMetadata', 'solid-core', moduleRef);
        this.entityManager = entityManager;
        this.repo = repo;
        this.moduleRef = moduleRef;
        this.cacheManager = cacheManager;
        this.logger = new common_1.Logger(PermissionMetadataService_1.name);
    }
    buildPermissionsByRoleCacheKey(roleName) {
        return `permissions:role:${roleName}`;
    }
    async findAllUsingRoles(roles) {
        const useCache = (0, cache_helper_1.shouldUseCache)();
        const cached = [];
        const uncachedRoles = [];
        if (useCache) {
            for (const role of roles) {
                const cacheKey = this.buildPermissionsByRoleCacheKey(role);
                const hit = await this.cacheManager.get(cacheKey);
                if (hit) {
                    cached.push(...hit);
                }
                else {
                    uncachedRoles.push(role);
                }
            }
        }
        else {
            uncachedRoles.push(...roles);
        }
        if (uncachedRoles.length === 0) {
            return cached;
        }
        const fromDb = await this.repo.find({
            where: { roles: { name: (0, typeorm_2.In)(uncachedRoles) } },
            relations: { roles: true },
        });
        if (useCache) {
            for (const role of uncachedRoles) {
                const permsForRole = fromDb.filter(p => p.roles?.some(r => r.name === role));
                await this.cacheManager.set(this.buildPermissionsByRoleCacheKey(role), permsForRole);
            }
        }
        const seen = new Set();
        return [...cached, ...fromDb].filter(p => {
            if (seen.has(p.id))
                return false;
            seen.add(p.id);
            return true;
        });
    }
    async permissionExistsInRole(role, permission) {
        const useCache = (0, cache_helper_1.shouldUseCache)();
        const cacheKey = this.buildPermissionsByRoleCacheKey(role);
        if (useCache) {
            const hit = await this.cacheManager.get(cacheKey);
            if (hit) {
                return hit.filter(p => p.name === permission);
            }
        }
        const fromDb = await this.repo.find({
            where: { roles: { name: role } },
            relations: { roles: true },
        });
        if (useCache) {
            await this.cacheManager.set(cacheKey, fromDb);
        }
        return fromDb.filter(p => p.name === permission);
    }
};
exports.PermissionMetadataService = PermissionMetadataService;
exports.PermissionMetadataService = PermissionMetadataService = PermissionMetadataService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectEntityManager)()),
    __param(3, (0, common_1.Inject)(cache_manager_1.CACHE_MANAGER)),
    __metadata("design:paramtypes", [typeorm_2.EntityManager,
        permission_metadata_repository_1.PermissionMetadataRepository,
        core_1.ModuleRef, Object])
], PermissionMetadataService);
//# sourceMappingURL=permission-metadata.service.js.map