"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "PermissionService", {
    enumerable: true,
    get: function() {
        return PermissionService;
    }
});
const _baseservice = require("./base.service");
const _entities = require("../../entities");
const _permissiondto = require("../interfaces/permission.dto");
const _runtimeexceptions = require("../../exceptions/runtime.exceptions");
const _authorizationconstants = require("../../constants/authorization.constants");
class PermissionService extends (0, _baseservice.BaseService)(_entities.Permission, _permissiondto.PermissionDto) {
    logger;
    _permissions = [];
    constructor({ loggerFactory, typeormService }){
        super({
            typeormService
        });
    }
    get permissions() {
        return this._permissions;
    }
    toDto(permission) {
        return {
            id: permission.id,
            name: permission.name
        };
    }
    authorizePermission(requiredPermission, assignedPermissions) {
        return !!assignedPermissions.find((assignedPermission)=>{
            const normalizePermission = this.normalizePermission(assignedPermission);
            if (!normalizePermission) return false;
            return normalizePermission === requiredPermission;
        });
    }
    async getPermissionByName(permissionName) {
        const permission = this.permissions.find((r)=>r.name === permissionName);
        if (!permission) throw new _runtimeexceptions.NotFoundException("Permission not found");
        return permission;
    }
    async getPermission(permissionId) {
        const permission = this.permissions.find((r)=>r.id === permissionId);
        if (!permission) throw new _runtimeexceptions.NotFoundException(`Permission by provided id is not found`);
        return permission;
    }
    async syncPermissions() {
        this._permissions = [];
        const permissionDefinition = (0, _authorizationconstants.flattenPermissionDefinition)();
        for (let permission of permissionDefinition){
            const storedPermission = await this.repository.findOneBy({
                name: permission
            });
            if (!storedPermission) {
                const newPermission = await this.create({
                    name: permission
                });
                this._permissions.push(newPermission);
            } else {
                this._permissions.push(storedPermission);
            }
        }
    }
    normalizePermission(assignedPermission) {
        const permissionInstance = this.permissions.find((r)=>r.id === assignedPermission || r.name === assignedPermission);
        if (!permissionInstance) {
            this.logger.warn(`The permission by provided id is not found. Skipping`);
            return;
        }
        return permissionInstance.name;
    }
}

//# sourceMappingURL=permission.service.js.map