<?php

declare(strict_types=1);

use Illuminate\Support\Collection;

it('declares default sorts for the standardized table surface inventory', function (): void {
    $paths = collect([
        'app/Filament/Resources/ManagedEnvironmentResource.php',
        'app/Filament/Resources/PolicyResource.php',
        'app/Filament/Resources/BackupSetResource.php',
        'app/Filament/Resources/BackupScheduleResource.php',
        'app/Filament/Resources/ProviderConnectionResource.php',
        'app/Filament/Resources/FindingResource.php',
        'app/Filament/Resources/OperationRunResource.php',
        'app/Filament/Resources/EntraGroupResource.php',
        'app/Filament/Resources/AlertDeliveryResource.php',
        'app/Filament/Resources/AlertRuleResource.php',
        'app/Filament/Resources/AlertDestinationResource.php',
        'app/Filament/Resources/BaselineProfileResource.php',
        'app/Filament/Resources/BaselineSnapshotResource.php',
        'app/Filament/Resources/InventoryItemResource.php',
        'app/Filament/Resources/PolicyVersionResource.php',
        'app/Filament/Resources/ReviewPackResource.php',
        'app/Filament/Resources/Workspaces/WorkspaceResource.php',
        'app/Filament/Resources/ManagedEnvironmentResource/RelationManagers/ManagedEnvironmentMembershipsRelationManager.php',
        'app/Filament/Resources/Workspaces/RelationManagers/WorkspaceMembershipsRelationManager.php',
        'app/Filament/Resources/BaselineProfileResource/RelationManagers/BaselineTenantAssignmentsRelationManager.php',
        'app/Filament/Resources/BackupSetResource/RelationManagers/BackupItemsRelationManager.php',
        'app/Filament/Resources/PolicyResource/RelationManagers/VersionsRelationManager.php',
        'app/Filament/Resources/BackupScheduleResource/RelationManagers/BackupScheduleOperationRunsRelationManager.php',
        'app/Filament/Pages/EnvironmentRequiredPermissions.php',
        'app/Filament/Pages/InventoryCoverage.php',
        'app/Filament/Pages/Monitoring/EvidenceOverview.php',
        'app/Filament/System/Pages/Directory/Tenants.php',
        'app/Filament/System/Pages/Directory/Workspaces.php',
        'app/Filament/System/Pages/Ops/Runs.php',
        'app/Filament/System/Pages/Ops/Failures.php',
        'app/Filament/System/Pages/Ops/Stuck.php',
        'app/Filament/System/Pages/Security/AccessLogs.php',
        'app/Filament/System/Pages/RepairWorkspaceOwners.php',
        'app/Filament/Widgets/Dashboard/RecentDriftFindings.php',
        'app/Filament/Widgets/Dashboard/RecentOperations.php',
        'app/Livewire/InventoryItemDependencyEdgesTable.php',
        'app/Livewire/BackupSetPolicyPickerTable.php',
        'app/Livewire/EntraGroupCachePickerTable.php',
        'app/Livewire/SettingsCatalogSettingsTable.php',
    ]);

    /** @var Collection<int, string> $missing */
    $missing = $paths
        ->filter(function (string $relativePath): bool {
            $contents = file_get_contents(base_path($relativePath));

            return ! is_string($contents) || ! str_contains($contents, '->defaultSort(');
        })
        ->values();

    expect($missing)->toBeEmpty('Missing explicit default sort declarations: '.implode(', ', $missing->all()));
});

it('declares domain-specific empty states across the standardized table surface inventory', function (): void {
    $patternByPath = [
        'app/Filament/Resources/ManagedEnvironmentResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/PolicyResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/BackupSetResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/BackupScheduleResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/ProviderConnectionResource/Pages/ListProviderConnections.php' => ['getTableEmptyStateHeading', 'getTableEmptyStateDescription'],
        'app/Filament/Resources/FindingResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/OperationRunResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/EntraGroupResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/AlertDeliveryResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/AlertRuleResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/AlertDestinationResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/BaselineProfileResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/BaselineSnapshotResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/InventoryItemResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/PolicyVersionResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/ReviewPackResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/Workspaces/WorkspaceResource.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/ManagedEnvironmentResource/RelationManagers/ManagedEnvironmentMembershipsRelationManager.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/Workspaces/RelationManagers/WorkspaceMembershipsRelationManager.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/BaselineProfileResource/RelationManagers/BaselineTenantAssignmentsRelationManager.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/BackupSetResource/RelationManagers/BackupItemsRelationManager.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/PolicyResource/RelationManagers/VersionsRelationManager.php' => ['->emptyStateHeading('],
        'app/Filament/Resources/BackupScheduleResource/RelationManagers/BackupScheduleOperationRunsRelationManager.php' => ['->emptyStateHeading('],
        'app/Filament/Pages/EnvironmentRequiredPermissions.php' => ['->emptyStateHeading('],
        'app/Filament/Pages/InventoryCoverage.php' => ['->emptyStateHeading('],
        'app/Filament/Pages/Monitoring/EvidenceOverview.php' => ['->emptyStateHeading('],
        'app/Filament/System/Pages/Directory/Tenants.php' => ['->emptyStateHeading('],
        'app/Filament/System/Pages/Directory/Workspaces.php' => ['->emptyStateHeading('],
        'app/Filament/System/Pages/Ops/Runs.php' => ['->emptyStateHeading('],
        'app/Filament/System/Pages/Ops/Failures.php' => ['->emptyStateHeading('],
        'app/Filament/System/Pages/Ops/Stuck.php' => ['->emptyStateHeading('],
        'app/Filament/System/Pages/Security/AccessLogs.php' => ['->emptyStateHeading('],
        'app/Filament/System/Pages/RepairWorkspaceOwners.php' => ['->emptyStateHeading('],
        'app/Filament/Widgets/Dashboard/RecentDriftFindings.php' => ['->emptyStateHeading('],
        'app/Filament/Widgets/Dashboard/RecentOperations.php' => ['->emptyStateHeading('],
        'app/Livewire/InventoryItemDependencyEdgesTable.php' => ['->emptyStateHeading('],
        'app/Livewire/BackupSetPolicyPickerTable.php' => ['->emptyStateHeading('],
        'app/Livewire/EntraGroupCachePickerTable.php' => ['->emptyStateHeading('],
        'app/Livewire/SettingsCatalogSettingsTable.php' => ['->emptyStateHeading('],
    ];

    $missing = [];

    foreach ($patternByPath as $relativePath => $patterns) {
        $contents = file_get_contents(base_path($relativePath));

        if (! is_string($contents)) {
            $missing[] = $relativePath;

            continue;
        }

        foreach ($patterns as $pattern) {
            if (! str_contains($contents, $pattern)) {
                $missing[] = $relativePath;

                break;
            }
        }
    }

    expect($missing)->toBeEmpty('Missing standardized empty-state declarations: '.implode(', ', $missing));
});

it('keeps persistence declarations explicit on the designated critical and follow-up filter surfaces', function (): void {
    $paths = [
        'app/Filament/Resources/ManagedEnvironmentResource.php',
        'app/Filament/Resources/PolicyResource.php',
        'app/Filament/Resources/BackupSetResource.php',
        'app/Filament/Resources/BackupScheduleResource.php',
        'app/Filament/Resources/ProviderConnectionResource.php',
        'app/Filament/Resources/FindingResource.php',
        'app/Filament/Resources/InventoryItemResource.php',
        'app/Filament/Resources/PolicyVersionResource.php',
        'app/Filament/Resources/RestoreRunResource.php',
        'app/Filament/Resources/AlertDeliveryResource.php',
        'app/Filament/Resources/EntraGroupResource.php',
        'app/Filament/Resources/OperationRunResource.php',
        'app/Filament/Resources/BaselineSnapshotResource.php',
        'app/Filament/Pages/EnvironmentRequiredPermissions.php',
        'app/Filament/Pages/Monitoring/EvidenceOverview.php',
        'app/Filament/Resources/BackupSetResource/RelationManagers/BackupItemsRelationManager.php',
    ];

    $missing = [];

    foreach ($paths as $relativePath) {
        $contents = file_get_contents(base_path($relativePath));

        if (! is_string($contents)) {
            $missing[] = $relativePath;

            continue;
        }

        foreach (['->persistSearchInSession()', '->persistSortInSession()', '->persistFiltersInSession()'] as $pattern) {
            if (! str_contains($contents, $pattern)) {
                $missing[] = "{$relativePath} ({$pattern})";
            }
        }
    }

    expect($missing)->toBeEmpty('Missing persistence declarations: '.implode(', ', $missing));
});

it('syncs canonical admin tenant filter state on the persisted admin list surfaces', function (): void {
    $patternByPath = [
        'app/Filament/Resources/BackupScheduleResource/Pages/ListBackupSchedules.php' => [
            'CanonicalAdminEnvironmentFilterState::class',
            '->sync(',
        ],
        'app/Filament/Resources/BackupSetResource/Pages/ListBackupSets.php' => [
            'CanonicalAdminEnvironmentFilterState::class',
            '->sync(',
        ],
        'app/Filament/Resources/FindingResource/Pages/ListFindings.php' => [
            'CanonicalAdminEnvironmentFilterState::class',
            '->sync(',
        ],
        'app/Filament/Resources/InventoryItemResource/Pages/ListInventoryItems.php' => [
            'CanonicalAdminEnvironmentFilterState::class',
            '->sync(',
        ],
        'app/Filament/Resources/RestoreRunResource/Pages/ListRestoreRuns.php' => [
            'CanonicalAdminEnvironmentFilterState::class',
            '->sync(',
        ],
        'app/Filament/Resources/PolicyResource/Pages/ListPolicies.php' => [
            'CanonicalAdminEnvironmentFilterState::class',
            '->sync(',
        ],
        'app/Filament/Resources/PolicyVersionResource/Pages/ListPolicyVersions.php' => [
            'CanonicalAdminEnvironmentFilterState::class',
            '->sync(',
        ],
        'app/Filament/Resources/EntraGroupResource/Pages/ListEntraGroups.php' => [
            'CanonicalAdminEnvironmentFilterState::class',
            '->sync(',
        ],
        'app/Filament/Pages/Monitoring/AuditLog.php' => [
            'CanonicalAdminEnvironmentFilterState::class',
            '->sync(',
        ],
    ];

    $missing = [];

    foreach ($patternByPath as $relativePath => $patterns) {
        $contents = file_get_contents(base_path($relativePath));

        if (! is_string($contents)) {
            $missing[] = $relativePath;

            continue;
        }

        foreach ($patterns as $pattern) {
            if (! str_contains($contents, $pattern)) {
                $missing[] = "{$relativePath} ({$pattern})";
            }
        }
    }

    expect($missing)->toBeEmpty('Missing canonical admin tenant filter sync coverage: '.implode(', ', $missing));
});

it('uses shared archived and date-range presets on the repeated soft-delete filter surfaces', function (): void {
    $patternByPath = [
        'app/Filament/Resources/PolicyVersionResource.php' => [
            'FilterPresets::dateRange(',
            'FilterPresets::archived()',
        ],
        'app/Filament/Resources/RestoreRunResource.php' => [
            'FilterPresets::dateRange(',
            'FilterPresets::archived()',
        ],
    ];

    $missing = [];

    foreach ($patternByPath as $relativePath => $patterns) {
        $contents = file_get_contents(base_path($relativePath));

        if (! is_string($contents)) {
            $missing[] = $relativePath;

            continue;
        }

        foreach ($patterns as $pattern) {
            if (! str_contains($contents, $pattern)) {
                $missing[] = "{$relativePath} ({$pattern})";
            }
        }
    }

    expect($missing)->toBeEmpty('Missing shared filter presets: '.implode(', ', $missing));
});

it('uses centralized option sources for the prioritized status and operation filters', function (): void {
    $patternByPath = [
        'app/Filament/Resources/FindingResource.php' => ['FilterOptionCatalog::findingStatuses()'],
        'app/Filament/Resources/AlertDeliveryResource.php' => ['FilterOptionCatalog::alertDeliveryStatuses()'],
        'app/Filament/Resources/BaselineProfileResource.php' => ['FilterOptionCatalog::baselineProfileStatuses()'],
        'app/Filament/Resources/OperationRunResource.php' => ['FilterOptionCatalog::operationTypes('],
    ];

    $missing = [];

    foreach ($patternByPath as $relativePath => $patterns) {
        $contents = file_get_contents(base_path($relativePath));

        if (! is_string($contents)) {
            $missing[] = $relativePath;

            continue;
        }

        foreach ($patterns as $pattern) {
            if (! str_contains($contents, $pattern)) {
                $missing[] = "{$relativePath} ({$pattern})";
            }
        }
    }

    expect($missing)->toBeEmpty('Missing centralized filter option sourcing: '.implode(', ', $missing));
});

it('uses the shared pagination profile helper on standardized surfaces', function (): void {
    $paths = [
        'app/Filament/Resources/ManagedEnvironmentResource.php',
        'app/Filament/Resources/PolicyResource.php',
        'app/Filament/Resources/BackupSetResource.php',
        'app/Filament/Resources/BackupScheduleResource.php',
        'app/Filament/Resources/ProviderConnectionResource.php',
        'app/Filament/Resources/FindingResource.php',
        'app/Filament/Resources/OperationRunResource.php',
        'app/Filament/Resources/EntraGroupResource.php',
        'app/Filament/Resources/AlertDeliveryResource.php',
        'app/Filament/Resources/AlertRuleResource.php',
        'app/Filament/Resources/AlertDestinationResource.php',
        'app/Filament/Resources/BaselineProfileResource.php',
        'app/Filament/Resources/BaselineSnapshotResource.php',
        'app/Filament/Resources/InventoryItemResource.php',
        'app/Filament/Resources/PolicyVersionResource.php',
        'app/Filament/Resources/ReviewPackResource.php',
        'app/Filament/Resources/Workspaces/WorkspaceResource.php',
        'app/Filament/Resources/ManagedEnvironmentResource/RelationManagers/ManagedEnvironmentMembershipsRelationManager.php',
        'app/Filament/Resources/Workspaces/RelationManagers/WorkspaceMembershipsRelationManager.php',
        'app/Filament/Resources/BaselineProfileResource/RelationManagers/BaselineTenantAssignmentsRelationManager.php',
        'app/Filament/Resources/BackupSetResource/RelationManagers/BackupItemsRelationManager.php',
        'app/Filament/Resources/PolicyResource/RelationManagers/VersionsRelationManager.php',
        'app/Filament/Resources/BackupScheduleResource/RelationManagers/BackupScheduleOperationRunsRelationManager.php',
        'app/Filament/Pages/EnvironmentRequiredPermissions.php',
        'app/Filament/Pages/InventoryCoverage.php',
        'app/Filament/Pages/Monitoring/EvidenceOverview.php',
        'app/Filament/System/Pages/Directory/Tenants.php',
        'app/Filament/System/Pages/Directory/Workspaces.php',
        'app/Filament/System/Pages/Ops/Runs.php',
        'app/Filament/System/Pages/Ops/Failures.php',
        'app/Filament/System/Pages/Ops/Stuck.php',
        'app/Filament/System/Pages/Security/AccessLogs.php',
        'app/Filament/System/Pages/RepairWorkspaceOwners.php',
        'app/Filament/Widgets/Dashboard/RecentDriftFindings.php',
        'app/Filament/Widgets/Dashboard/RecentOperations.php',
        'app/Livewire/InventoryItemDependencyEdgesTable.php',
        'app/Livewire/BackupSetPolicyPickerTable.php',
        'app/Livewire/EntraGroupCachePickerTable.php',
        'app/Livewire/SettingsCatalogSettingsTable.php',
    ];

    $missing = collect($paths)
        ->filter(function (string $relativePath): bool {
            $contents = file_get_contents(base_path($relativePath));

            return ! is_string($contents) || ! str_contains($contents, 'TablePaginationProfiles::');
        })
        ->values()
        ->all();

    expect($missing)->toBeEmpty('Missing pagination profile helper usage: '.implode(', ', $missing));
});

it('keeps spec 196 surfaces on native table contracts without faux controls or hand-built primary tables', function (): void {
    $requiredPatterns = [
        'app/Filament/Pages/EnvironmentRequiredPermissions.php' => [
            'implements HasTable',
            'InteractsWithTable',
        ],
        'app/Filament/Pages/Monitoring/EvidenceOverview.php' => [
            'implements HasTable',
            'InteractsWithTable',
        ],
        'app/Livewire/InventoryItemDependencyEdgesTable.php' => [
            'extends TableComponent',
        ],
        'resources/views/filament/components/dependency-edges.blade.php' => [
            'inventory-item-dependency-edges-table',
        ],
        'resources/views/filament/pages/environment-required-permissions.blade.php' => [
            '$this->table',
            'data-testid="technical-details"',
        ],
        'resources/views/filament/pages/monitoring/evidence-overview.blade.php' => [
            '$this->table',
        ],
    ];

    $forbiddenPatterns = [
        'resources/views/filament/components/dependency-edges.blade.php' => [
            '<form method="GET"',
            'request(',
        ],
        'resources/views/filament/pages/environment-required-permissions.blade.php' => [
            'wire:model.live="status"',
            'wire:model.live="type"',
            'wire:model.live="features"',
            'wire:model.live.debounce.500ms="search"',
            '<table class="min-w-full divide-y divide-gray-200 dark:divide-gray-800">',
        ],
        'resources/views/filament/pages/monitoring/evidence-overview.blade.php' => [
            '<table class="min-w-full divide-y divide-gray-200 text-sm">',
        ],
    ];

    $missing = [];
    $unexpected = [];

    foreach ($requiredPatterns as $relativePath => $patterns) {
        $contents = file_get_contents(base_path($relativePath));

        if (! is_string($contents)) {
            $missing[] = $relativePath;

            continue;
        }

        foreach ($patterns as $pattern) {
            if (! str_contains($contents, $pattern)) {
                $missing[] = "{$relativePath} ({$pattern})";
            }
        }
    }

    foreach ($forbiddenPatterns as $relativePath => $patterns) {
        $contents = file_get_contents(base_path($relativePath));

        if (! is_string($contents)) {
            continue;
        }

        foreach ($patterns as $pattern) {
            if (str_contains($contents, $pattern)) {
                $unexpected[] = "{$relativePath} ({$pattern})";
            }
        }
    }

    expect($missing)->toBeEmpty('Missing native table contract patterns: '.implode(', ', $missing))
        ->and($unexpected)->toBeEmpty('Unexpected faux-control or hand-built table patterns remain: '.implode(', ', $unexpected));
});

it('keeps tenant-registry recovery triage columns, filters, and query hydration explicit', function (): void {
    $patternByPath = [
        'app/Filament/Resources/ManagedEnvironmentResource.php' => [
            "TextColumn::make('backup_posture')",
            "TextColumn::make('recovery_evidence')",
            "SelectFilter::make('backup_posture')",
            "SelectFilter::make('recovery_evidence')",
            "SelectFilter::make('triage_sort')",
            'applyWorstFirstTriageOrdering',
            'postureSnapshot',
        ],
        'app/Filament/Resources/ManagedEnvironmentResource/Pages/ListManagedEnvironments.php' => [
            'applyRequestedTriageIntent',
            'getTableEmptyStateHeading',
            'getTableEmptyStateDescription',
        ],
    ];

    $missing = [];

    foreach ($patternByPath as $relativePath => $patterns) {
        $contents = file_get_contents(base_path($relativePath));

        if (! is_string($contents)) {
            $missing[] = $relativePath;

            continue;
        }

        foreach ($patterns as $pattern) {
            if (! str_contains($contents, $pattern)) {
                $missing[] = "{$relativePath} ({$pattern})";
            }
        }
    }

    expect($missing)->toBeEmpty('Missing tenant registry triage table contracts: '.implode(', ', $missing));
});
