<?php

declare(strict_types=1);

use App\Filament\Pages\Monitoring\Operations;
use App\Filament\Resources\BackupScheduleResource\Pages\ListBackupSchedules;
use App\Filament\Resources\BackupSetResource\Pages\EditBackupSet;
use App\Filament\Resources\BackupSetResource\Pages\ListBackupSets;
use App\Filament\Resources\BackupSetResource\RelationManagers\BackupItemsRelationManager;
use App\Filament\Resources\FindingResource\Pages\ListFindings;
use App\Filament\Resources\PolicyResource\Pages\ListPolicies;
use App\Filament\Resources\ProviderConnectionResource\Pages\ListProviderConnections;
use App\Filament\Resources\ManagedEnvironmentResource\Pages\ListManagedEnvironments;
use App\Models\BackupSet;
use App\Support\Filament\TablePaginationProfiles;
use Filament\Facades\Filament;
use Filament\Tables\Table;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Features\SupportTesting\Testable;
use Livewire\Livewire;

uses(RefreshDatabase::class);

function spec125CriticalTable(Testable $component): Table
{
    return $component->instance()->getTable();
}

/**
 * @return array{0: \App\Models\User, 1: \App\Models\ManagedEnvironment}
 */
function spec125CriticalTenantContext(bool $ensureDefaultMicrosoftProviderConnection = true): array
{
    [$user, $tenant] = createUserWithTenant(
        role: 'owner',
        ensureDefaultMicrosoftProviderConnection: $ensureDefaultMicrosoftProviderConnection,
    );

    test()->actingAs($user);
    setAdminPanelContext($tenant);

    return [$user, $tenant];
}

it('standardizes the tenant list defaults around searchable identity and hidden detail', function (): void {
    [$user] = spec125CriticalTenantContext();

    setAdminPanelContext();

    $component = Livewire::actingAs($user)->test(ListManagedEnvironments::class)
        ->assertTableEmptyStateActionsExistInOrder(['add_tenant']);

    $table = spec125CriticalTable($component);

    expect($table->getPaginationPageOptions())->toBe(TablePaginationProfiles::resource());
    expect($table->persistsSearchInSession())->toBeTrue();
    expect($table->persistsSortInSession())->toBeTrue();
    expect($table->persistsFiltersInSession())->toBeTrue();
    expect($table->getEmptyStateHeading())->toBe('No tenants connected');
    expect($table->getEmptyStateDescription())->toBe('Add a tenant to start syncing inventory, policies, and provider health into this workspace.');
    expect($table->getColumn('name')?->isSearchable())->toBeTrue();
    expect($table->getColumn('name')?->isSortable())->toBeTrue();
    expect($table->getColumn('managed_environment_id')?->isToggleable())->toBeTrue();
    expect($table->getColumn('managed_environment_id')?->isToggledHiddenByDefault())->toBeTrue();
    expect($table->getColumn('domain')?->isToggleable())->toBeTrue();
    expect($table->getColumn('domain')?->isToggledHiddenByDefault())->toBeTrue();
    expect($table->getColumn('created_at')?->isToggleable())->toBeTrue();
    expect($table->getColumn('created_at')?->isToggledHiddenByDefault())->toBeTrue();
    expect(count($table->getVisibleColumns()))->toBeLessThanOrEqual(7);
});

it('standardizes the policy list defaults around calm scanning and persistence', function (): void {
    [$user, $tenant] = spec125CriticalTenantContext();

    setAdminPanelContext($tenant);

    $component = Livewire::actingAs($user)->test(ListPolicies::class)
        ->assertTableEmptyStateActionsExistInOrder(['sync']);

    $table = spec125CriticalTable($component);

    expect($table->getDefaultSortColumn())->toBe('display_name');
    expect($table->getDefaultSortDirection())->toBe('asc');
    expect($table->getPaginationPageOptions())->toBe(TablePaginationProfiles::resource());
    expect($table->persistsSearchInSession())->toBeTrue();
    expect($table->persistsSortInSession())->toBeTrue();
    expect($table->persistsFiltersInSession())->toBeTrue();
    expect($table->getColumn('display_name')?->isSearchable())->toBeTrue();
    expect($table->getColumn('display_name')?->isSortable())->toBeTrue();
    expect($table->getColumn('external_id')?->isToggleable())->toBeTrue();
    expect($table->getColumn('external_id')?->isToggledHiddenByDefault())->toBeTrue();
    expect(count($table->getVisibleColumns()))->toBeLessThanOrEqual(7);
});

it('standardizes the backup-set list around recency and toggle-hidden operational detail', function (): void {
    [$user, $tenant] = spec125CriticalTenantContext();

    setAdminPanelContext($tenant);

    $component = Livewire::actingAs($user)->test(ListBackupSets::class)
        ->assertTableEmptyStateActionsExistInOrder(['create']);

    $table = spec125CriticalTable($component);

    expect($table->getDefaultSortColumn())->toBe('created_at');
    expect($table->getDefaultSortDirection())->toBe('desc');
    expect($table->getPaginationPageOptions())->toBe(TablePaginationProfiles::resource());
    expect($table->persistsSearchInSession())->toBeTrue();
    expect($table->persistsSortInSession())->toBeTrue();
    expect($table->persistsFiltersInSession())->toBeTrue();
    expect($table->getEmptyStateHeading())->toBe('No backup sets');
    expect($table->getColumn('name')?->isSearchable())->toBeTrue();
    expect($table->getColumn('name')?->isSortable())->toBeTrue();
    expect($table->getColumn('item_count')?->isSortable())->toBeTrue();
    expect($table->getColumn('created_by')?->isToggleable())->toBeTrue();
    expect($table->getColumn('created_by')?->isToggledHiddenByDefault())->toBeTrue();
    expect($table->getColumn('created_at')?->isToggleable())->toBeTrue();
    expect($table->getColumn('created_at')?->isToggledHiddenByDefault())->toBeTrue();
    expect(count($table->getVisibleColumns()))->toBeLessThanOrEqual(7);
});

it('standardizes the backup-schedule list around next-run ordering and hidden secondary detail', function (): void {
    [$user, $tenant] = spec125CriticalTenantContext();

    setAdminPanelContext($tenant);

    $component = Livewire::actingAs($user)->test(ListBackupSchedules::class)
        ->assertTableEmptyStateActionsExistInOrder(['create']);

    $table = spec125CriticalTable($component);

    expect($table->getDefaultSortColumn())->toBe('next_run_at');
    expect($table->getDefaultSortDirection())->toBe('asc');
    expect($table->getPaginationPageOptions())->toBe(TablePaginationProfiles::resource());
    expect($table->persistsSearchInSession())->toBeTrue();
    expect($table->persistsSortInSession())->toBeTrue();
    expect($table->persistsFiltersInSession())->toBeTrue();
    expect($table->getEmptyStateHeading())->toBe('No schedules configured');
    expect($table->getColumn('name')?->isSearchable())->toBeTrue();
    expect($table->getColumn('name')?->isSortable())->toBeTrue();
    expect($table->getColumn('timezone')?->isToggleable())->toBeTrue();
    expect($table->getColumn('timezone')?->isToggledHiddenByDefault())->toBeTrue();
    expect($table->getColumn('retention_keep_last')?->isToggleable())->toBeTrue();
    expect($table->getColumn('retention_keep_last')?->isToggledHiddenByDefault())->toBeTrue();
    expect($table->getColumn('last_run_status')?->isToggleable())->toBeTrue();
    expect($table->getColumn('last_run_status')?->isToggledHiddenByDefault())->toBeTrue();
    expect(count($table->getVisibleColumns()))->toBeLessThanOrEqual(7);
});

it('standardizes the provider-connections list around searchable names and tenant-safe empty states', function (): void {
    [$user, $tenant] = spec125CriticalTenantContext(ensureDefaultMicrosoftProviderConnection: false);

    setAdminPanelContext($tenant);

    $component = Livewire::actingAs($user)->test(ListProviderConnections::class)
        ->assertTableEmptyStateActionsExistInOrder(['create']);

    $table = spec125CriticalTable($component);

    expect($table->getDefaultSortColumn())->toBe('display_name');
    expect($table->getDefaultSortDirection())->toBe('asc');
    expect($table->getPaginationPageOptions())->toBe(TablePaginationProfiles::resource());
    expect($table->persistsSearchInSession())->toBeTrue();
    expect($table->persistsSortInSession())->toBeTrue();
    expect($table->persistsFiltersInSession())->toBeTrue();
    expect($table->getEmptyStateHeading())->toBe('No provider connections found');
    expect($table->getEmptyStateDescription())->toBe('Start with a platform-managed provider connection. Dedicated overrides are handled separately with stronger authorization.');
    expect($table->getColumn('display_name')?->isSearchable())->toBeTrue();
    expect($table->getColumn('display_name')?->isSortable())->toBeTrue();
    expect($table->getColumn('provider')?->isToggleable())->toBeFalse();
    expect($table->getColumn('provider')?->isToggledHiddenByDefault())->toBeFalse();
    expect($table->getColumn('target_scope')?->getLabel())->toBe('Target scope');
    expect($table->getColumn('entra_tenant_id')?->getLabel())->toBe('Microsoft tenant ID');
    expect($table->getColumn('entra_tenant_id')?->isToggleable())->toBeTrue();
    expect($table->getColumn('entra_tenant_id')?->isToggledHiddenByDefault())->toBeTrue();
    expect($table->getColumn('last_error_reason_code')?->isToggleable())->toBeTrue();
    expect($table->getColumn('last_error_reason_code')?->isToggledHiddenByDefault())->toBeTrue();
    expect($table->getColumn('last_error_message')?->isToggleable())->toBeTrue();
    expect($table->getColumn('last_error_message')?->isToggledHiddenByDefault())->toBeTrue();
    expect(count($table->getVisibleColumns()))->toBeLessThanOrEqual(9);
});

it('standardizes the findings list around open triage work with hidden forensic detail', function (): void {
    [$user, $tenant] = spec125CriticalTenantContext();

    setAdminPanelContext($tenant);

    $component = Livewire::actingAs($user)->test(ListFindings::class);
    $table = spec125CriticalTable($component);

    expect($table->getDefaultSortColumn())->toBe('created_at');
    expect($table->getDefaultSortDirection())->toBe('desc');
    expect($table->getPaginationPageOptions())->toBe(TablePaginationProfiles::resource());
    expect($table->persistsSearchInSession())->toBeTrue();
    expect($table->persistsSortInSession())->toBeTrue();
    expect($table->persistsFiltersInSession())->toBeTrue();
    expect($table->getEmptyStateHeading())->toBe('No findings match this view');
    expect($table->getColumn('subject_display_name')?->isSearchable())->toBeTrue();
    expect($table->getColumn('due_at')?->isSortable())->toBeTrue();
    expect($table->getColumn('evidence_fidelity')?->isToggleable())->toBeTrue();
    expect($table->getColumn('evidence_fidelity')?->isToggledHiddenByDefault())->toBeTrue();
    expect($table->getColumn('subject_type')?->isToggleable())->toBeTrue();
    expect($table->getColumn('subject_type')?->isToggledHiddenByDefault())->toBeTrue();
    expect($table->getColumn('subject_external_id')?->isToggleable())->toBeTrue();
    expect($table->getColumn('subject_external_id')?->isToggledHiddenByDefault())->toBeTrue();
    expect($table->getColumn('scope_key')?->isToggleable())->toBeTrue();
    expect($table->getColumn('scope_key')?->isToggledHiddenByDefault())->toBeTrue();
    expect(count($table->getVisibleColumns()))->toBeLessThanOrEqual(8);
});

it('standardizes the monitoring operations view through the operation-run resource table contract', function (): void {
    [$user, $tenant] = spec125CriticalTenantContext();

    setAdminPanelContext($tenant);

    $component = Livewire::actingAs($user)->test(Operations::class);
    $table = spec125CriticalTable($component);

    expect($table->getDefaultSortColumn())->toBe('created_at');
    expect($table->getDefaultSortDirection())->toBe('desc');
    expect($table->getPaginationPageOptions())->toBe(TablePaginationProfiles::resource());
    expect($table->persistsSearchInSession())->toBeTrue();
    expect($table->persistsSortInSession())->toBeTrue();
    expect($table->persistsFiltersInSession())->toBeTrue();
    expect($table->getEmptyStateHeading())->toBe('No operations found');
    expect($table->getEmptyStateDescription())->toBe('Queued, running, and completed operations will appear here when work is triggered in this scope.');
    expect($table->getEmptyStateActions())->toBeEmpty();
    expect($table->getColumn('type')?->isSearchable())->toBeTrue();
    expect($table->getColumn('type')?->isSortable())->toBeTrue();
    expect($table->getColumn('created_at')?->isSortable())->toBeTrue();
    expect(count($table->getVisibleColumns()))->toBeLessThanOrEqual(7);
});

it('standardizes the backup-items relation manager without disturbing its action surface', function (): void {
    [$user, $tenant] = spec125CriticalTenantContext();

    setAdminPanelContext($tenant);

    $backupSet = BackupSet::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
    ]);

    $component = Livewire::actingAs($user)->test(BackupItemsRelationManager::class, [
        'ownerRecord' => $backupSet,
        'pageClass' => EditBackupSet::class,
    ])
        ->assertTableEmptyStateActionsExistInOrder(['addPoliciesEmpty']);

    $table = spec125CriticalTable($component);

    expect($table->getDefaultSortColumn())->toBe('policy.display_name');
    expect($table->getDefaultSortDirection())->toBe('asc');
    expect($table->getPaginationPageOptions())->toBe(TablePaginationProfiles::relationManager());
    expect($table->getEmptyStateHeading())->toBe('No policies in this backup set');
    expect($table->getEmptyStateDescription())->toBe('Add policies to capture versions and assignments inside this backup set.');
    expect($table->getColumn('policy.display_name')?->isSearchable())->toBeTrue();
    expect($table->getColumn('policy.display_name')?->isSortable())->toBeTrue();
    expect($table->getColumn('policy_identifier')?->isToggleable())->toBeTrue();
    expect($table->getColumn('policy_identifier')?->isToggledHiddenByDefault())->toBeTrue();
    expect($table->getColumn('scope_tags')?->isToggleable())->toBeTrue();
    expect($table->getColumn('scope_tags')?->isToggledHiddenByDefault())->toBeTrue();
    expect($table->getColumn('captured_at')?->isToggleable())->toBeTrue();
    expect($table->getColumn('captured_at')?->isToggledHiddenByDefault())->toBeTrue();
    expect($table->getColumn('created_at')?->isToggleable())->toBeTrue();
    expect($table->getColumn('created_at')?->isToggledHiddenByDefault())->toBeTrue();
});
