"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AccessRoleResolver = void 0;
const lodash_1 = require("lodash");
const typeorm_1 = require("typeorm");
const platform_access_entity_1 = require("../../user/entities/platform-access.entity");
const user_access_entity_1 = require("../../user/entities/user-access.entity");
const role_mapper_util_1 = require("./role-mapper.util");
const auth_config_service_1 = require("../../core/services/auth-config.service");
const request_context_1 = require("../../request-context");
class AccessRoleResolver {
    static async resolveRolesAndPermissionsForTenantContext(params) {
        const { userId, tenantId } = params;
        const platformAccess = await user_access_entity_1.NestAuthUserAccess.findOne({
            where: {
                userId,
                tenantId: tenantId == null ? (0, typeorm_1.IsNull)() : tenantId,
            },
            relations: ['roles', 'roles.rolePermissions', 'roles.rolePermissions.permission'],
        });
        const mergedRoles = platformAccess?.roles ?? [];
        const uniqRoleMap = new Map(mergedRoles.map((r) => [r.id, r]));
        const roles = Array.from(uniqRoleMap.values());
        const permissions = (0, lodash_1.chain)(roles)
            .map((role) => (0, role_mapper_util_1.getRolePermissionNames)(role))
            .flatten()
            .uniq()
            .value();
        return { roles, permissions };
    }
    static async isPlatformAccess() {
        const authConfig = auth_config_service_1.AuthConfigService.getOptions();
        if (authConfig.platformAccess?.enabled === true) {
            return await authConfig.platformAccess.validate(request_context_1.RequestContext.currentRequest());
        }
        else {
            return false;
        }
    }
    static async resolvePlatformAccess(userId) {
        const platformAccess = await platform_access_entity_1.NestAuthPlatformAccess.findOne({
            where: { userId, isActive: true },
            relations: ['roles'],
        });
        return platformAccess?.roles ?? [];
    }
    static async resolvePlatformAccessRolesAndPermissions(userId) {
        const tenantAccess = await this.resolvePlatformAccess(userId);
        const roles = tenantAccess ?? [];
        const permissions = (0, lodash_1.chain)(roles)
            .map((role) => (0, role_mapper_util_1.getRolePermissionNames)(role))
            .flatten()
            .uniq()
            .value();
        return { roles, permissions };
    }
    static async isPlatformAdminUser(userId) {
        const platformAccessRoles = await this.resolvePlatformAccess(userId);
        return (platformAccessRoles?.length ?? 0) > 0;
    }
}
exports.AccessRoleResolver = AccessRoleResolver;
//# sourceMappingURL=access-role-resolver.util.js.map