<?php

declare(strict_types=1);

use App\Filament\Resources\EnvironmentReviewResource;
use App\Models\ManagedEnvironment;
use App\Models\Workspace;
use Tests\Support\OpsUx\SourceFileScanner;

/**
 * @return list<string>
 */
function governanceArtifactLegacyTenantGuardedFiles(): array
{
    $root = SourceFileScanner::projectRoot();

    return [
        $root.'/app/Filament/Pages/Reviews/CustomerReviewWorkspace.php',
        $root.'/app/Filament/Pages/Reviews/ReviewRegister.php',
        $root.'/app/Filament/Resources/BackupScheduleResource.php',
        $root.'/app/Filament/Resources/BackupSetResource.php',
        $root.'/app/Filament/Resources/EvidenceSnapshotResource.php',
        $root.'/app/Filament/Resources/FindingExceptionResource.php',
        $root.'/app/Filament/Resources/FindingResource.php',
        $root.'/app/Filament/Resources/InventoryItemResource.php',
        $root.'/app/Filament/Resources/PolicyResource.php',
        $root.'/app/Filament/Resources/PolicyVersionResource.php',
        $root.'/app/Filament/Resources/RestoreRunResource.php',
        $root.'/app/Filament/Resources/ReviewPackResource.php',
        $root.'/app/Filament/Resources/StoredReportResource.php',
        $root.'/app/Filament/Resources/EnvironmentReviewResource.php',
        $root.'/app/Support/GovernanceInbox/GovernanceInboxSectionBuilder.php',
        $root.'/app/Support/Navigation/RelatedNavigationResolver.php',
        $root.'/app/Support/OperationRunLinks.php',
        $root.'/app/Support/SupportDiagnostics/SupportDiagnosticBundleBuilder.php',
        $root.'/app/Support/Ui/GovernanceArtifactTruth/ArtifactTruthPresenter.php',
    ];
}

/**
 * @return list<array{pattern: string, reason: string}>
 */
function governanceArtifactLegacyTenantForbiddenPatterns(): array
{
    return [
        [
            'pattern' => "/panel:\\s*'tenant'/",
            'reason' => 'Touched governance artifact surfaces must not emit tenant-panel URLs directly.',
        ],
        [
            'pattern' => '/\\/admin\\/t\\//',
            'reason' => 'Touched governance artifact surfaces must not hardcode legacy /admin/t route language.',
        ],
        [
            'pattern' => '/\\bManagedEnvironment::current\\s*\\(/',
            'reason' => 'Touched governance artifact surfaces must not rely on tenant-panel-only current-environment fallbacks.',
        ],
        [
            'pattern' => '/\\bFilament::getTenant\\s*\\(/',
            'reason' => 'Touched governance artifact surfaces must resolve admin context through the shared panel resolver, not raw Filament tenant reads.',
        ],
        [
            'pattern' => "/getCurrentPanel\\(\\)\\?->getId\\(\\)\\s*===\\s*'admin'/",
            'reason' => 'Touched governance artifact resources must not stay hidden behind admin-only registration guards.',
        ],
    ];
}

it('keeps touched governance artifact sources free of tenant-panel route language and fallback guards', function (): void {
    $violations = [];

    foreach (governanceArtifactLegacyTenantGuardedFiles() as $path) {
        $source = SourceFileScanner::read($path);
        $lines = preg_split('/\R/', $source) ?: [];

        foreach ($lines as $index => $line) {
            foreach (governanceArtifactLegacyTenantForbiddenPatterns() as $pattern) {
                if (preg_match($pattern['pattern'], $line) !== 1) {
                    continue;
                }

                $violations[] = [
                    'file' => SourceFileScanner::relativePath($path),
                    'line' => $index + 1,
                    'snippet' => SourceFileScanner::snippet($source, $index + 1),
                    'reason' => $pattern['reason'],
                ];
            }
        }
    }

    expect($violations)->toBeEmpty();
})->group('surface-guard');

it('keeps environment review scoped urls on workspace-first admin routes', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner', setUiContext: false);

    $snapshot = seedEnvironmentReviewEvidence($tenant);
    $review = composeEnvironmentReviewForTest($tenant, $user, $snapshot);
    $workspace = Workspace::query()->whereKey((int) $tenant->workspace_id)->firstOrFail();

    setAdminPanelContext();

    $path = parse_url(
        EnvironmentReviewResource::environmentScopedUrl('view', ['record' => $review], $tenant),
        PHP_URL_PATH,
    );

    expect($path)
        ->toBe('/admin/workspaces/'.$workspace->getRouteKey().'/environments/'.$tenant->getRouteKey().'/environment-reviews/'.$review->getRouteKey())
        ->not->toContain('/admin/t/');
})->group('surface-guard');
