"use strict";
/**
 * E2E Test: Enhanced Access Control Generator
 *
 * This test verifies that the enhanced access control generator actually writes
 * all expected authorization files to disk with correct content.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
require("../generators/index"); // Ensure all generators are registered
const generation_orchestrator_1 = require("../generators/generation-orchestrator");
describe('E2E: Enhanced Access Control Generator', () => {
    const testOutputDir = path.join(__dirname, '../../.e2e-output/enhanced-access-control');
    let orchestrator;
    beforeEach(() => {
        if (fs.existsSync(testOutputDir)) {
            fs.rmSync(testOutputDir, { recursive: true, force: true });
        }
        orchestrator = new generation_orchestrator_1.GenerationOrchestrator();
    });
    afterEach(() => {
        if (fs.existsSync(testOutputDir)) {
            fs.rmSync(testOutputDir, { recursive: true, force: true });
        }
    });
    it('should generate all access control files for RBAC model', async () => {
        const workflow = {
            workflow: {
                id: 'e2e-access-control-test',
                version: '1.0.0',
                name: 'E2E Access Control Test',
                description: 'Testing enhanced access control generator E2E',
            },
            stack: {
                web: { type: 'frontend', technology: 'react', config: { port: 5173 } },
                api: { type: 'backend', technology: 'typescript/express', config: { port: 3000 } },
            },
            access_control: {
                model: 'rbac',
                roles: [
                    {
                        name: 'admin',
                        permissions: [
                            { resource: 'users', actions: ['read', 'write', 'delete'] },
                            { resource: 'posts', actions: ['read', 'write', 'delete'] },
                        ],
                    },
                    {
                        name: 'editor',
                        permissions: [{ resource: 'posts', actions: ['read', 'write'] }],
                    },
                ],
            },
            stages: { local: { infrastructure: { databases: {}, services: {} } } },
        };
        const _result = await orchestrator.generate(workflow, {
            outputDirectory: testOutputDir,
            dryRun: false,
            verbose: false,
        });
        expect(_result.files.length).toBeGreaterThan(0);
        const expectedFiles = [
            'api/src/types/access-control.ts',
            'api/src/config/roles.ts',
            'api/src/services/rbac.ts',
            'api/src/middleware/authorization.ts',
            'api/src/utils/auth-decorators.ts',
            'web/src/types/permissions.ts',
            'web/src/hooks/usePermissions.ts',
            'web/src/components/Can.tsx',
            'web/src/providers/AuthorizationProvider.tsx',
        ];
        expectedFiles.forEach(expectedFile => {
            const fullPath = path.join(testOutputDir, expectedFile);
            expect(fs.existsSync(fullPath)).toBe(true);
        });
    });
    it('should generate RBAC service with correct methods', async () => {
        const workflow = {
            workflow: { id: 'rbac-test', version: '1.0.0', name: 'RBAC Test' },
            stack: { api: { type: 'backend', technology: 'typescript/express' } },
            access_control: {
                model: 'rbac',
                roles: [{ name: 'user', permissions: [{ resource: 'profile', actions: ['read', 'write'] }] }],
            },
            stages: { local: { infrastructure: { databases: {}, services: {} } } },
        };
        const _result = await orchestrator.generate(workflow, {
            outputDirectory: testOutputDir,
            dryRun: false,
            verbose: false,
        });
        const rbacPath = path.join(testOutputDir, 'api/src/services/rbac.ts');
        expect(fs.existsSync(rbacPath)).toBe(true);
        const rbac = fs.readFileSync(rbacPath, 'utf-8');
        expect(rbac).toContain('RBACService');
        expect(rbac).toContain('can(');
        expect(rbac).toContain('getUserPermissions');
        expect(rbac).toContain('hasRole');
        expect(rbac).toContain('hasAllRoles');
        expect(rbac).toContain('getAccessibleResources');
    });
    it('should generate ABAC service with condition evaluation', async () => {
        const workflow = {
            workflow: { id: 'abac-test', version: '1.0.0', name: 'ABAC Test' },
            stack: { api: { type: 'backend', technology: 'typescript/express' } },
            access_control: {
                model: 'abac',
                roles: [
                    {
                        name: 'manager',
                        permissions: [
                            {
                                resource: 'reports',
                                actions: ['read'],
                                conditions: [{ field: 'user.department', operator: 'equals', value: 'sales' }],
                            },
                        ],
                    },
                ],
            },
            stages: { local: { infrastructure: { databases: {}, services: {} } } },
        };
        const _result = await orchestrator.generate(workflow, {
            outputDirectory: testOutputDir,
            dryRun: false,
            verbose: false,
        });
        const abacPath = path.join(testOutputDir, 'api/src/services/abac.ts');
        expect(fs.existsSync(abacPath)).toBe(true);
        const abac = fs.readFileSync(abacPath, 'utf-8');
        expect(abac).toContain('ABACService');
        expect(abac).toContain('evaluateCondition');
        expect(abac).toContain('evaluateConditions');
        expect(abac).toContain('authorize');
    });
    it('should generate hybrid authorization for rbac_with_abac model', async () => {
        const workflow = {
            workflow: { id: 'hybrid-test', version: '1.0.0', name: 'Hybrid Test' },
            stack: { api: { type: 'backend', technology: 'typescript/express' } },
            access_control: {
                model: 'rbac_with_abac',
                roles: [
                    {
                        name: 'hr_manager',
                        permissions: [
                            {
                                resource: 'employees',
                                actions: ['read', 'write'],
                                conditions: [{ field: 'user.attributes.department', operator: 'equals', value: 'HR' }],
                            },
                        ],
                    },
                ],
            },
            stages: { local: { infrastructure: { databases: {}, services: {} } } },
        };
        const _result = await orchestrator.generate(workflow, {
            outputDirectory: testOutputDir,
            dryRun: false,
            verbose: false,
        });
        expect(fs.existsSync(path.join(testOutputDir, 'api/src/services/rbac.ts'))).toBe(true);
        expect(fs.existsSync(path.join(testOutputDir, 'api/src/services/abac.ts'))).toBe(true);
        expect(fs.existsSync(path.join(testOutputDir, 'api/src/services/authorization.ts'))).toBe(true);
        const authService = fs.readFileSync(path.join(testOutputDir, 'api/src/services/authorization.ts'), 'utf-8');
        expect(authService).toContain('AuthorizationService');
        expect(authService).toContain('rbacService');
        expect(authService).toContain('abacService');
    });
    it('should generate role configuration with permissions', async () => {
        const workflow = {
            workflow: { id: 'roles-test', version: '1.0.0', name: 'Roles Test' },
            stack: { api: { type: 'backend', technology: 'typescript/express' } },
            access_control: {
                model: 'rbac',
                roles: [
                    {
                        name: 'moderator',
                        permissions: [
                            { resource: 'comments', actions: ['read', 'delete'] },
                            { resource: 'posts', actions: ['read'] },
                        ],
                    },
                ],
            },
            stages: { local: { infrastructure: { databases: {}, services: {} } } },
        };
        const _result = await orchestrator.generate(workflow, {
            outputDirectory: testOutputDir,
            dryRun: false,
            verbose: false,
        });
        const rolesPath = path.join(testOutputDir, 'api/src/config/roles.ts');
        expect(fs.existsSync(rolesPath)).toBe(true);
        const roles = fs.readFileSync(rolesPath, 'utf-8');
        expect(roles).toContain('moderator');
        expect(roles).toContain('comments');
        expect(roles).toContain('posts');
        expect(roles).toContain('getRoleByName');
        expect(roles).toContain('getRolePermissions');
    });
    it('should generate authorization middleware', async () => {
        const workflow = {
            workflow: { id: 'middleware-test', version: '1.0.0', name: 'Middleware Test' },
            stack: { api: { type: 'backend', technology: 'typescript/express' } },
            access_control: {
                model: 'rbac',
                roles: [{ name: 'user', permissions: [{ resource: 'api', actions: ['access'] }] }],
            },
            stages: { local: { infrastructure: { databases: {}, services: {} } } },
        };
        const _result = await orchestrator.generate(workflow, {
            outputDirectory: testOutputDir,
            dryRun: false,
            verbose: false,
        });
        const middlewarePath = path.join(testOutputDir, 'api/src/middleware/authorization.ts');
        expect(fs.existsSync(middlewarePath)).toBe(true);
        const middleware = fs.readFileSync(middlewarePath, 'utf-8');
        expect(middleware).toContain('authorize(');
        expect(middleware).toContain('requireRole');
        expect(middleware).toContain('requireAllRoles');
        expect(middleware).toContain('Unauthorized');
        expect(middleware).toContain('Forbidden');
    });
    it('should generate policy engine when policies defined', async () => {
        const workflow = {
            workflow: { id: 'policy-test', version: '1.0.0', name: 'Policy Test' },
            stack: { api: { type: 'backend', technology: 'typescript/express' } },
            access_control: {
                model: 'rbac',
                roles: [],
                policies: [
                    {
                        name: 'admin_delete_users',
                        resource: 'users',
                        action: 'delete',
                        rules: [{ role: 'admin' }],
                    },
                ],
            },
            stages: { local: { infrastructure: { databases: {}, services: {} } } },
        };
        const _result = await orchestrator.generate(workflow, {
            outputDirectory: testOutputDir,
            dryRun: false,
            verbose: false,
        });
        const policyPath = path.join(testOutputDir, 'api/src/services/policy-engine.ts');
        expect(fs.existsSync(policyPath)).toBe(true);
        const policy = fs.readFileSync(policyPath, 'utf-8');
        expect(policy).toContain('PolicyEngine');
        expect(policy).toContain('evaluatePolicy');
        expect(policy).toContain('admin_delete_users');
    });
    it('should generate React permission hooks', async () => {
        const workflow = {
            workflow: { id: 'hooks-test', version: '1.0.0', name: 'Hooks Test' },
            stack: { web: { type: 'frontend', technology: 'react' } },
            access_control: {
                model: 'rbac',
                roles: [{ name: 'viewer', permissions: [{ resource: 'content', actions: ['view'] }] }],
            },
            stages: { local: { infrastructure: { databases: {}, services: {} } } },
        };
        const _result = await orchestrator.generate(workflow, {
            outputDirectory: testOutputDir,
            dryRun: false,
            verbose: false,
        });
        const hooksPath = path.join(testOutputDir, 'web/src/hooks/usePermissions.ts');
        expect(fs.existsSync(hooksPath)).toBe(true);
        const hooks = fs.readFileSync(hooksPath, 'utf-8');
        expect(hooks).toContain('useCan');
        expect(hooks).toContain('usePermissions');
        expect(hooks).toContain('useRole');
        expect(hooks).toContain('AuthorizationContext');
    });
    it('should generate Can component for conditional rendering', async () => {
        const workflow = {
            workflow: { id: 'can-test', version: '1.0.0', name: 'Can Test' },
            stack: { web: { type: 'frontend', technology: 'react' } },
            access_control: {
                model: 'rbac',
                roles: [{ name: 'author', permissions: [{ resource: 'articles', actions: ['create', 'edit'] }] }],
            },
            stages: { local: { infrastructure: { databases: {}, services: {} } } },
        };
        const _result = await orchestrator.generate(workflow, {
            outputDirectory: testOutputDir,
            dryRun: false,
            verbose: false,
        });
        const canPath = path.join(testOutputDir, 'web/src/components/Can.tsx');
        expect(fs.existsSync(canPath)).toBe(true);
        const can = fs.readFileSync(canPath, 'utf-8');
        expect(can).toContain('Can:');
        expect(can).toContain('Cannot:');
        expect(can).toContain('perform');
        expect(can).toContain('fallback');
    });
    it('should generate authorization provider', async () => {
        const workflow = {
            workflow: { id: 'provider-test', version: '1.0.0', name: 'Provider Test' },
            stack: { web: { type: 'frontend', technology: 'react' } },
            access_control: {
                model: 'rbac',
                roles: [{ name: 'subscriber', permissions: [{ resource: 'premium', actions: ['access'] }] }],
            },
            stages: { local: { infrastructure: { databases: {}, services: {} } } },
        };
        const _result = await orchestrator.generate(workflow, {
            outputDirectory: testOutputDir,
            dryRun: false,
            verbose: false,
        });
        const providerPath = path.join(testOutputDir, 'web/src/providers/AuthorizationProvider.tsx');
        expect(fs.existsSync(providerPath)).toBe(true);
        const provider = fs.readFileSync(providerPath, 'utf-8');
        expect(provider).toContain('AuthorizationProvider');
        expect(provider).toContain('AuthorizationContext');
        expect(provider).toContain('fetchPermissions');
        expect(provider).toContain('/api/auth/permissions');
    });
    it('should generate permission types with resource and action types', async () => {
        const workflow = {
            workflow: { id: 'types-test', version: '1.0.0', name: 'Types Test' },
            stack: { web: { type: 'frontend', technology: 'react' } },
            access_control: {
                model: 'rbac',
                roles: [
                    {
                        name: 'developer',
                        permissions: [
                            { resource: 'code', actions: ['read', 'write'] },
                            { resource: 'deploy', actions: ['execute'] },
                        ],
                    },
                ],
            },
            stages: { local: { infrastructure: { databases: {}, services: {} } } },
        };
        const _result = await orchestrator.generate(workflow, {
            outputDirectory: testOutputDir,
            dryRun: false,
            verbose: false,
        });
        const typesPath = path.join(testOutputDir, 'web/src/types/permissions.ts');
        expect(fs.existsSync(typesPath)).toBe(true);
        const types = fs.readFileSync(typesPath, 'utf-8');
        expect(types).toContain('type Resource');
        expect(types).toContain('type Action');
        expect(types).toContain('code');
        expect(types).toContain('deploy');
    });
});
//# sourceMappingURL=enhanced-access-control.e2e.test.js.map