<?php

use Illuminate\Filesystem\Filesystem;

it('does not use role-string checks outside the RBAC core', function () {
    /**
     * This guard test is intentionally narrow:
     * - It targets comparisons / branching on role strings (authorization-by-role patterns).
     * - It does NOT forbid role literals used as data values (e.g., form options, seed data).
     */
    $allowedFiles = collect([
        app_path('Services/Auth/RoleCapabilityMap.php'),
        app_path('Services/Auth/ManagedEnvironmentMembershipManager.php'),
    ])->map(fn (string $path) => realpath($path) ?: $path)->all();

    $roleValuePattern = '(owner|manager|operator|readonly)';

    $patterns = [
        // $membership->role === 'owner' / !== 'owner'
        '/->role\s*(===|==|!==|!=)\s*(["\'])'.$roleValuePattern.'\2/i',

        // $role === 'owner'
        '/\$role\s*(===|==|!==|!=)\s*(["\'])'.$roleValuePattern.'\2/i',

        // case 'owner':
        '/\bcase\s*(["\'])'.$roleValuePattern.'\1\s*:/i',

        // match (...) { 'owner' => ... }
        '/\bmatch\b[\s\S]*?\{[\s\S]*?(["\'])'.$roleValuePattern.'\1\s*=>/i',
    ];

    $filesystem = new Filesystem;

    $violations = [];

    foreach ($filesystem->allFiles(app_path()) as $file) {
        $path = $file->getRealPath();

        if ($path === false) {
            continue;
        }

        if (in_array($path, $allowedFiles, true)) {
            continue;
        }

        $contents = $filesystem->get($path);

        foreach ($patterns as $pattern) {
            if (preg_match($pattern, $contents) === 1) {
                $violations[] = $path;
                break;
            }
        }
    }

    if ($violations !== []) {
        throw new RuntimeException('Role-string checks must live in RoleCapabilityMap / ManagedEnvironmentMembershipManager only. Offenders: '.implode(', ', $violations));
    }

    expect($violations)->toBeEmpty();
});
