"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable no-console */
const ability_1 = require("@casl/ability");
const organizationMemberProfile_1 = require("../types/organizationMemberProfile");
const projectMemberRole_1 = require("../types/projectMemberRole");
const index_1 = require("./index");
const projectMemberAbility_1 = require("./projectMemberAbility");
const projectMemberAbility_mock_1 = require("./projectMemberAbility.mock");
const roleToScopeMapping_1 = require("./roleToScopeMapping");
const roleToScopeMapping_testUtils_1 = require("./roleToScopeMapping.testUtils");
const scopeAbilityBuilder_1 = require("./scopeAbilityBuilder");
describe('roleToScopeMapping', () => {
    describe('isSystemRole', () => {
        it('should return true for valid system role "developer"', () => {
            expect((0, roleToScopeMapping_1.isSystemRole)('developer')).toBe(true);
        });
        it('should return false for invalid role "1234"', () => {
            expect((0, roleToScopeMapping_1.isSystemRole)('1234')).toBe(false);
        });
        it('should return true for all valid ProjectMemberRole values', () => {
            expect((0, roleToScopeMapping_1.isSystemRole)('viewer')).toBe(true);
            expect((0, roleToScopeMapping_1.isSystemRole)('interactive_viewer')).toBe(true);
            expect((0, roleToScopeMapping_1.isSystemRole)('editor')).toBe(true);
            expect((0, roleToScopeMapping_1.isSystemRole)('developer')).toBe(true);
            expect((0, roleToScopeMapping_1.isSystemRole)('admin')).toBe(true);
        });
        it('should return false for invalid strings', () => {
            expect((0, roleToScopeMapping_1.isSystemRole)('')).toBe(false);
            expect((0, roleToScopeMapping_1.isSystemRole)('invalid-role')).toBe(false);
            expect((0, roleToScopeMapping_1.isSystemRole)('custom-uuid-123')).toBe(false);
            expect((0, roleToScopeMapping_1.isSystemRole)('VIEWER')).toBe(false); // Case sensitive
            expect((0, roleToScopeMapping_1.isSystemRole)('Developer')).toBe(false); // Case sensitive
        });
        it('should work as a type guard', () => {
            const roleUuid = 'developer';
            if ((0, roleToScopeMapping_1.isSystemRole)(roleUuid)) {
                // TypeScript should now know that roleUuid is ProjectMemberRole
                expect(typeof roleUuid).toBe('string');
                expect(roleUuid).toBe('developer');
            }
            else {
                fail('isSystemRole should return true for "developer"');
            }
        });
    });
    describe('getScopesForRole', () => {
        it('should return scopes for viewer role', () => {
            const scopes = (0, roleToScopeMapping_1.getAllScopesForRole)(projectMemberRole_1.ProjectMemberRole.VIEWER);
            expect(scopes).toContain('view:Dashboard');
            expect(scopes).toContain('view:SavedChart');
            expect(scopes).toContain('view:Space');
            expect(scopes).toContain('view:Project');
        });
        it('should include inherited scopes for editor role', () => {
            const scopes = (0, roleToScopeMapping_1.getAllScopesForRole)(projectMemberRole_1.ProjectMemberRole.EDITOR);
            // Should have viewer scopes
            expect(scopes).toContain('view:Dashboard');
            expect(scopes).toContain('view:SavedChart');
            // Should have interactive viewer scopes
            expect(scopes).toContain('view:UnderlyingData');
            expect(scopes).toContain('manage:Explore');
            expect(scopes).toContain('create:ScheduledDeliveries');
            expect(scopes).toContain('manage:ScheduledDeliveries@self');
            // Should have editor-specific scopes
            expect(scopes).toContain('create:Space');
            expect(scopes).toContain('manage:DashboardComments');
        });
        it('should have more scopes for higher roles', () => {
            const viewerScopes = (0, roleToScopeMapping_1.getAllScopesForRole)(projectMemberRole_1.ProjectMemberRole.VIEWER);
            const editorScopes = (0, roleToScopeMapping_1.getAllScopesForRole)(projectMemberRole_1.ProjectMemberRole.EDITOR);
            const adminScopes = (0, roleToScopeMapping_1.getAllScopesForRole)(projectMemberRole_1.ProjectMemberRole.ADMIN);
            expect(editorScopes.length).toBeGreaterThan(viewerScopes.length);
            expect(adminScopes.length).toBeGreaterThan(editorScopes.length);
        });
    });
    describe('validateRoleInheritance', () => {
        it('should validate that roles properly inherit permissions', () => {
            const validation = (0, roleToScopeMapping_testUtils_1.validateRoleInheritance)();
            if (!validation.valid) {
                console.debug('Validation errors:', validation.errors);
            }
            expect(validation.valid).toBe(true);
            expect(validation.errors).toHaveLength(0);
        });
    });
    describe('debugRoleScopeMapping', () => {
        it('should not throw when debugging editor role', () => {
            expect(() => {
                (0, roleToScopeMapping_testUtils_1.debugRoleScopeMapping)(projectMemberRole_1.ProjectMemberRole.EDITOR);
            }).not.toThrow();
        });
    });
    describe('AbilityBuilderCompatibility', () => { });
    describe('Ability builder compatibility', () => {
        it('should build equivalent abilities using scopes vs role-based builder', () => {
            // Build ability using the old role-based system
            const roleBuilder = new ability_1.AbilityBuilder(ability_1.Ability);
            projectMemberAbility_1.projectMemberAbilities[projectMemberRole_1.ProjectMemberRole.EDITOR](projectMemberAbility_mock_1.PROJECT_EDITOR, roleBuilder);
            const roleAbility = roleBuilder.build();
            // Define scopes that should be equivalent to an editor role
            // Based on projectMemberAbility.ts, an editor can:
            // - Do everything interactive_viewer can do (view content, export, create deliveries & manage own deliveries)
            // - Create spaces
            // - Manage non-private spaces, jobs, pinned items, scheduled deliveries, dashboard comments, tags
            // NOTE: Adding manage:Project to enable managing non-private spaces
            const editorScopes = [
                // Interactive viewer scopes (inherited)
                'view:Dashboard',
                'view:SavedChart',
                'view:Space',
                'view:Project',
                'create:ScheduledDeliveries',
                'manage:ScheduledDeliveries@self',
                'view:Job',
                'create:Job',
                'manage:Explore',
                'create:DashboardComments',
                // Editor-specific scopes
                'create:Space',
                'manage:Space',
                'manage:Project', // Required for managing non-private spaces
                'manage:Job',
                'manage:PinnedItems',
                'manage:DashboardComments',
                'manage:Tags',
            ];
            // Build ability using the new scope-based system
            const scopeBuilder = new ability_1.AbilityBuilder(ability_1.Ability);
            (0, scopeAbilityBuilder_1.buildAbilityFromScopes)({
                projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid,
                userUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.userUuid,
                scopes: editorScopes,
                isEnterprise: false,
                organizationRole: 'editor',
                permissionsConfig: {
                    pat: {
                        enabled: false,
                        allowedOrgRoles: [],
                    },
                },
            }, scopeBuilder);
            const scopeAbility = scopeBuilder.build();
            // Test cases that should be equivalent for both abilities
            const testCases = [
                // View permissions (inherited from interactive_viewer)
                {
                    action: 'view',
                    subject: 'Dashboard',
                    resource: {
                        organizationUuid: 'org-uuid-test',
                        projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid,
                        inheritsFromOrgOrProject: true,
                    },
                },
                {
                    action: 'view',
                    subject: 'SavedChart',
                    resource: {
                        organizationUuid: 'org-uuid-test',
                        projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid,
                        inheritsFromOrgOrProject: true,
                    },
                },
                {
                    action: 'view',
                    subject: 'Space',
                    resource: {
                        organizationUuid: 'org-uuid-test',
                        projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid,
                        inheritsFromOrgOrProject: true,
                    },
                },
                // Create permissions (editor-specific)
                {
                    action: 'create',
                    subject: 'Space',
                    resource: {
                        organizationUuid: 'org-uuid-test',
                        projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid,
                    },
                },
                // Manage permissions (editor-specific)
                {
                    action: 'manage',
                    subject: 'Space',
                    resource: {
                        organizationUuid: 'org-uuid-test',
                        projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid,
                        inheritsFromOrgOrProject: true,
                    },
                },
                {
                    action: 'manage',
                    subject: 'Job',
                    resource: {},
                },
                {
                    action: 'manage',
                    subject: 'PinnedItems',
                    resource: {
                        organizationUuid: 'org-uuid-test',
                        projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid,
                    },
                },
                {
                    action: 'manage',
                    subject: 'ScheduledDeliveries',
                    resource: {
                        organizationUuid: 'org-uuid-test',
                        projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid,
                    },
                },
                {
                    action: 'manage',
                    subject: 'DashboardComments',
                    resource: {
                        organizationUuid: 'org-uuid-test',
                        projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid,
                    },
                },
                {
                    action: 'manage',
                    subject: 'Tags',
                    resource: {
                        organizationUuid: 'org-uuid-test',
                        projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid,
                    },
                },
            ];
            // Verify that both ability builders produce the same results
            testCases.forEach(({ action, subject: subjectType, resource }) => {
                const subjectWithResource = (0, ability_1.subject)(subjectType, resource);
                const roleResult = roleAbility.can(action, subjectWithResource);
                const scopeResult = scopeAbility.can(action, subjectWithResource);
                expect(scopeResult).toBe(roleResult);
            });
        });
        it('should deny the same permissions for both abilities', () => {
            // Build abilities
            const roleBuilder = new ability_1.AbilityBuilder(ability_1.Ability);
            projectMemberAbility_1.projectMemberAbilities[projectMemberRole_1.ProjectMemberRole.EDITOR](projectMemberAbility_mock_1.PROJECT_EDITOR, roleBuilder);
            const roleAbility = roleBuilder.build();
            const editorScopes = [
                'view:Dashboard',
                'view:SavedChart',
                'view:Space',
                'view:Project',
                'create:ScheduledDeliveries',
                'view:Job',
                'create:Job',
                'manage:Explore',
                'create:DashboardComments',
                'create:Space',
                'manage:Job',
                'manage:PinnedItems',
                'manage:ScheduledDeliveries',
                'manage:DashboardComments',
                'manage:Tags',
            ];
            const scopeBuilder = new ability_1.AbilityBuilder(ability_1.Ability);
            (0, scopeAbilityBuilder_1.buildAbilityFromScopes)({
                projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid,
                userUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.userUuid,
                scopes: editorScopes,
                isEnterprise: false,
                organizationRole: 'editor',
                permissionsConfig: {
                    pat: {
                        enabled: false,
                        allowedOrgRoles: [],
                    },
                },
            }, scopeBuilder);
            const scopeAbility = scopeBuilder.build();
            // Test cases that should be denied for both abilities (editor limitations)
            const deniedTestCases = [
                // Cannot manage project (developer+ only)
                {
                    action: 'manage',
                    subject: 'Project',
                    resource: { projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid },
                },
                // Cannot manage validations (developer+ only)
                {
                    action: 'manage',
                    subject: 'Validation',
                    resource: { projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid },
                },
                // Cannot manage virtual views (developer+ only)
                {
                    action: 'manage',
                    subject: 'VirtualView',
                    resource: { projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid },
                },
            ];
            // Verify that both ability builders deny the same permissions
            deniedTestCases.forEach(({ action, subject: subjectType, resource }) => {
                const subjectWithResource = (0, ability_1.subject)(subjectType, resource);
                const roleResult = roleAbility.can(action, subjectWithResource);
                const scopeResult = scopeAbility.can(action, subjectWithResource);
                expect(scopeResult).toBe(roleResult);
                expect(roleResult).toBe(false); // Ensure they're both false
            });
        });
    });
    describe('Convert all project member roles to scopes', () => {
        const testCases = [
            {
                action: 'view',
                subject: 'Dashboard',
                resource: {
                    organizationUuid: 'org-uuid-test',
                    projectUuid: 'test-project-uuid',
                    inheritsFromOrgOrProject: true,
                },
            },
            {
                action: 'create',
                subject: 'Space',
                resource: {
                    organizationUuid: 'org-uuid-test',
                    projectUuid: 'test-project-uuid',
                },
            },
            {
                action: 'manage',
                subject: 'Space',
                resource: {
                    organizationUuid: 'org-uuid-test',
                    projectUuid: 'test-project-uuid',
                    inheritsFromOrgOrProject: true,
                },
            },
            {
                action: 'manage',
                subject: 'Project',
                resource: { projectUuid: 'test-project-uuid' },
            },
            {
                action: 'view',
                subject: 'Analytics',
                resource: { projectUuid: 'test-project-uuid' },
            },
        ];
        const roles = [
            projectMemberRole_1.ProjectMemberRole.VIEWER,
            projectMemberRole_1.ProjectMemberRole.INTERACTIVE_VIEWER,
            projectMemberRole_1.ProjectMemberRole.EDITOR,
            projectMemberRole_1.ProjectMemberRole.DEVELOPER,
            projectMemberRole_1.ProjectMemberRole.ADMIN,
        ];
        roles.forEach((role) => {
            it(`should have equivalent CASL abilities for ${role} role`, () => {
                // Build role-based ability
                const roleBuilder = new ability_1.AbilityBuilder(ability_1.Ability);
                const testMember = {
                    role,
                    projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid,
                    userUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.userUuid,
                };
                projectMemberAbility_1.projectMemberAbilities[role](testMember, roleBuilder);
                const roleAbility = roleBuilder.build();
                // Build scope-based ability
                const scopes = (0, roleToScopeMapping_1.getNonEnterpriseScopesForRole)(role);
                const scopeBuilder = new ability_1.AbilityBuilder(ability_1.Ability);
                (0, scopeAbilityBuilder_1.buildAbilityFromScopes)({
                    projectUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.projectUuid,
                    userUuid: projectMemberAbility_mock_1.PROJECT_EDITOR.userUuid,
                    scopes,
                    isEnterprise: false,
                    organizationRole: 'editor',
                    permissionsConfig: {
                        pat: {
                            enabled: false,
                            allowedOrgRoles: [],
                        },
                    },
                }, scopeBuilder);
                const scopeAbility = scopeBuilder.build();
                // Test key permissions for each role - assert strict equivalence
                testCases.forEach((testCase) => {
                    const subjectWithResource = (0, ability_1.subject)(testCase.subject, testCase.resource);
                    const roleResult = roleAbility.can(testCase.action, subjectWithResource);
                    const scopeResult = scopeAbility.can(testCase.action, subjectWithResource);
                    // Assert that both systems return the same result with detailed context
                    if (scopeResult !== roleResult) {
                        throw new Error(`Permission mismatch for ${role} role:\n` +
                            `  Action: ${testCase.action}\n` +
                            `  Subject: ${testCase.subject}\n` +
                            `  Resource: ${JSON.stringify(testCase.resource, null, 2)}\n` +
                            `  Role-based result: ${roleResult}\n` +
                            `  Scope-based result: ${scopeResult}\n` +
                            `  Expected: Both systems should return ${roleResult}`);
                    }
                    expect(scopeResult).toBe(roleResult);
                });
            });
        });
    });
    describe('Combined Organization and Project Roles', () => {
        const testCases = [
            {
                action: 'view',
                subject: 'Dashboard',
                resource: {
                    organizationUuid: 'org-uuid-test',
                    projectUuid: 'project-uuid-test',
                    inheritsFromOrgOrProject: true,
                },
            },
            {
                action: 'create',
                subject: 'Space',
                resource: {
                    organizationUuid: 'org-uuid-test',
                    projectUuid: 'project-uuid-test',
                },
            },
            {
                action: 'manage',
                subject: 'Space',
                resource: {
                    organizationUuid: 'org-uuid-test',
                    projectUuid: 'project-uuid-test',
                    inheritsFromOrgOrProject: true,
                },
            },
            {
                action: 'manage',
                subject: 'Project',
                resource: { projectUuid: 'project-uuid-test' },
            },
            {
                action: 'manage',
                subject: 'Validation',
                resource: { projectUuid: 'project-uuid-test' },
            },
            {
                action: 'view',
                subject: 'Analytics',
                resource: { projectUuid: 'project-uuid-test' },
            },
        ];
        const roleCombinations = [
            {
                description: 'viewer org + viewer project',
                orgRole: organizationMemberProfile_1.OrganizationMemberRole.VIEWER,
                projectRole: projectMemberRole_1.ProjectMemberRole.VIEWER,
            },
            {
                description: 'viewer org + developer project',
                orgRole: organizationMemberProfile_1.OrganizationMemberRole.VIEWER,
                projectRole: projectMemberRole_1.ProjectMemberRole.DEVELOPER,
            },
            {
                description: 'editor org + developer project',
                orgRole: organizationMemberProfile_1.OrganizationMemberRole.EDITOR,
                projectRole: projectMemberRole_1.ProjectMemberRole.DEVELOPER,
            },
            {
                description: 'developer org + admin project',
                orgRole: organizationMemberProfile_1.OrganizationMemberRole.DEVELOPER,
                projectRole: projectMemberRole_1.ProjectMemberRole.ADMIN,
            },
            {
                description: 'viewer org + admin project',
                orgRole: organizationMemberProfile_1.OrganizationMemberRole.VIEWER,
                projectRole: projectMemberRole_1.ProjectMemberRole.ADMIN,
            },
        ];
        roleCombinations.forEach(({ description, orgRole, projectRole }) => {
            it(`should have equivalent abilities for ${description}`, () => {
                const user = {
                    role: orgRole,
                    organizationUuid: 'org-uuid-test',
                    userUuid: 'user-uuid-test',
                    roleUuid: undefined,
                };
                const projectProfiles = [
                    {
                        projectUuid: 'project-uuid-test',
                        role: projectRole,
                        userUuid: 'user-uuid-test',
                        roleUuid: undefined,
                    },
                ];
                // Build ability using the combined role-based system
                const { builder: roleBasedBuilder } = (0, index_1.getUserAbilityBuilder)({
                    user,
                    projectProfiles,
                    permissionsConfig: {
                        pat: {
                            enabled: false,
                            allowedOrgRoles: [],
                        },
                    },
                    customRoleScopes: {},
                    customRolesEnabled: false,
                    isEnterprise: false,
                });
                const roleBasedAbility = roleBasedBuilder.build();
                // Build equivalent scope-based ability
                // Convert OrganizationMemberRole to ProjectMemberRole for scope mapping
                // Note: This is a simplification - in reality, org roles may have different scope mappings
                const orgRoleAsProjectRole = orgRole;
                const orgScopes = (0, roleToScopeMapping_1.getNonEnterpriseScopesForRole)(orgRoleAsProjectRole);
                const projectScopes = (0, roleToScopeMapping_1.getNonEnterpriseScopesForRole)(projectRole);
                const allScopes = [
                    ...new Set([...orgScopes, ...projectScopes]),
                ]; // Remove duplicates
                const scopeBuilder = new ability_1.AbilityBuilder(ability_1.Ability);
                (0, scopeAbilityBuilder_1.buildAbilityFromScopes)({
                    organizationUuid: 'org-uuid-test',
                    userUuid: 'user-uuid-test',
                    scopes: orgScopes,
                    isEnterprise: false,
                    organizationRole: orgRole,
                    permissionsConfig: {
                        pat: {
                            enabled: false,
                            allowedOrgRoles: [],
                        },
                    },
                }, scopeBuilder);
                (0, scopeAbilityBuilder_1.buildAbilityFromScopes)({
                    projectUuid: projectProfiles[0].projectUuid,
                    userUuid: 'user-uuid-test',
                    scopes: projectScopes,
                    isEnterprise: false,
                    organizationRole: orgRole,
                    permissionsConfig: {
                        pat: {
                            enabled: false,
                            allowedOrgRoles: [],
                        },
                    },
                }, scopeBuilder);
                const scopeBasedAbility = scopeBuilder.build();
                // Test each permission combination
                testCases.forEach((testCase) => {
                    const subjectWithResource = (0, ability_1.subject)(testCase.subject, testCase.resource);
                    const roleBasedResult = roleBasedAbility.can(testCase.action, subjectWithResource);
                    const scopeBasedResult = scopeBasedAbility.can(testCase.action, subjectWithResource);
                    // Provide detailed error information for mismatches
                    if (roleBasedResult !== scopeBasedResult) {
                        throw new Error(`Permission mismatch for ${description}:\n` +
                            `  Action: ${testCase.action}\n` +
                            `  Subject: ${testCase.subject}\n` +
                            `  Resource: ${JSON.stringify(testCase.resource, null, 2)}\n` +
                            `  Role-based result: ${roleBasedResult}\n` +
                            `  Scope-based result: ${scopeBasedResult}\n` +
                            `  Organization role: ${orgRole}\n` +
                            `  Project role: ${projectRole}\n` +
                            `  Combined scopes: ${allScopes.length} scopes\n` +
                            `  Expected: Both systems should return ${roleBasedResult}`);
                    }
                    expect(scopeBasedResult).toBe(roleBasedResult);
                });
            });
        });
    });
});
//# sourceMappingURL=roleToScopeMapping.test.js.map