<?php

declare(strict_types=1);

use App\Filament\Pages\InventoryCoverage;
use App\Filament\Resources\FindingResource;
use App\Filament\Resources\PolicyResource\Pages\ListPolicies;
use App\Filament\Resources\PolicyResource\Pages\ViewPolicy;
use App\Filament\Resources\PolicyResource\RelationManagers\VersionsRelationManager;
use App\Filament\Widgets\Dashboard\RecentDriftFindings;
use App\Livewire\EntraGroupCachePickerTable;
use App\Models\Finding;
use App\Models\Policy;
use App\Support\Filament\TablePaginationProfiles;
use Filament\Facades\Filament;
use Filament\Tables\Table;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\App;
use Livewire\Features\SupportTesting\Testable;
use Livewire\Livewire;

uses(RefreshDatabase::class);

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

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

    test()->actingAs($user);
    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    return [$user, $tenant];
}

it('keeps the policy resource list as the baseline resource-standard example', function (): void {
    App::setLocale('en');

    [$user] = spec125BaselineTenantContext();

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

    $table = spec125BaselineTable($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(__('localization.policy.resource.empty_state_heading'));
    expect($table->getEmptyStateDescription())->toBe(__('localization.policy.resource.empty_state_description'));
    expect(array_keys($table->getVisibleColumns()))->toContain('display_name', 'policy_type', 'platform', 'last_synced_at');

    $displayName = $table->getColumn('display_name');
    $externalId = $table->getColumn('external_id');

    expect($displayName)->not->toBeNull();
    expect($displayName?->isSearchable())->toBeTrue();
    expect($displayName?->isSortable())->toBeTrue();
    expect($externalId)->not->toBeNull();
    expect($externalId?->isToggleable())->toBeTrue();
    expect($externalId?->isToggledHiddenByDefault())->toBeTrue();
    expect(array_keys($table->getVisibleColumns()))->not->toContain('external_id');
});

it('keeps the policy versions relation manager on the standard relation-manager contract', function (): void {
    App::setLocale('en');

    [$user, $tenant] = spec125BaselineTenantContext();

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

    $component = Livewire::actingAs($user)->test(VersionsRelationManager::class, [
        'ownerRecord' => $policy,
        'pageClass' => ViewPolicy::class,
    ]);

    $table = spec125BaselineTable($component);

    expect($table->getDefaultSortColumn())->toBe('version_number');
    expect($table->getDefaultSortDirection())->toBe('desc');
    expect($table->getPaginationPageOptions())->toBe(TablePaginationProfiles::relationManager());
    expect($table->getEmptyStateHeading())->toBe(__('localization.policy.relation.no_versions_captured'));
    expect($table->getEmptyStateDescription())->toBe(__('localization.policy.relation.no_versions_captured_description'));
    expect($table->getColumn('version_number')?->isSortable())->toBeTrue();
    expect($table->getColumn('captured_at')?->isSortable())->toBeTrue();
    expect($table->getColumn('policy_type')?->isToggleable())->toBeTrue();
    expect($table->getColumn('policy_type')?->isToggledHiddenByDefault())->toBeTrue();
});

it('keeps the dashboard widget profile minimal and scan-first', function (): void {
    [$user, $tenant] = spec125BaselineTenantContext();

    $finding = Finding::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'finding_type' => Finding::FINDING_TYPE_DRIFT,
    ]);

    $component = Livewire::actingAs($user)->test(RecentDriftFindings::class);
    $table = spec125BaselineTable($component);

    expect($table->getDefaultSortColumn())->toBe('created_at');
    expect($table->getDefaultSortDirection())->toBe('desc');
    expect($table->getPaginationPageOptions())->toBe(TablePaginationProfiles::widget());
    expect($table->getEmptyStateHeading())->toBe('No drift findings');
    expect($table->getEmptyStateDescription())->toBe('You\'re looking good — no drift findings to review yet.');
    expect(array_keys($table->getVisibleColumns()))->toBe([
        'short_id',
        'subject_display_name',
        'severity',
        'created_at',
    ]);
    expect($table->getColumn('status')?->isToggleable())->toBeTrue();
    expect($table->getColumn('status')?->isToggledHiddenByDefault())->toBeTrue();
    expect($table->getColumn('severity')?->isSortable())->toBeTrue();
    expect($table->getColumn('created_at')?->isSortable())->toBeTrue();
    expect($table->getRecordUrl($finding))->toBe(
        FindingResource::getUrl('view', ['record' => $finding], tenant: $tenant)
    );
});

it('keeps custom table pages on their explicit profile without hidden framework defaults', function (): void {
    [$user] = spec125BaselineTenantContext();

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

    $table = spec125BaselineTable($component);

    expect($table->getDefaultSortColumn())->toBe('follow_up_priority');
    expect($table->getDefaultSortDirection())->toBe('asc');
    expect($table->getPaginationPageOptions())->toBe(TablePaginationProfiles::customPage());
    expect($table->getEmptyStateHeading())->toBe('No coverage rows match this report');
    expect($table->getEmptyStateDescription())->toBe('Clear the current search or filters to return to the full tenant coverage report.');
    expect($table->getColumn('type')?->isSortable())->toBeTrue();
    expect($table->getColumn('label')?->isSortable())->toBeTrue();
    expect($table->getColumn('dependencies')?->isToggleable())->toBeTrue();
});

it('keeps picker tables workflow-local while still following the shared picker defaults', function (): void {
    [$user] = spec125BaselineTenantContext();

    $component = Livewire::actingAs($user)->test(EntraGroupCachePickerTable::class, [
        'sourceGroupId' => 'source-group-1',
    ]);

    $table = spec125BaselineTable($component);

    expect($table->getDefaultSortColumn())->toBe('display_name');
    expect($table->getDefaultSortDirection())->toBe('asc');
    expect($table->getPaginationPageOptions())->toBe(TablePaginationProfiles::picker());
    expect($table->getEmptyStateHeading())->toBe('No cached groups found');
    expect($table->getEmptyStateDescription())->toBe('Run “Sync Groups” first, then come back here.');
    expect($table->persistsSearchInSession())->toBeFalse();
    expect($table->persistsSortInSession())->toBeFalse();
    expect($table->persistsFiltersInSession())->toBeFalse();
    expect($table->getColumn('display_name')?->isSearchable())->toBeTrue();
    expect($table->getColumn('display_name')?->isSortable())->toBeTrue();
    expect($table->getColumn('entra_id')?->isToggleable())->toBeTrue();
    expect($table->getColumn('entra_id')?->isToggledHiddenByDefault())->toBeTrue();
});
