<?php

declare(strict_types=1);

use App\Filament\Resources\ProviderConnectionResource;
use App\Filament\Resources\ProviderConnectionResource\Pages\ListProviderConnections;
use App\Models\ProviderConnection;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('keeps provider connection list and detail surfaces centered on target scope', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner', ensureDefaultMicrosoftProviderConnection: false);

    $connection = ProviderConnection::factory()->consentGranted()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'display_name' => 'Spec 281 visible connection',
        'entra_tenant_id' => '66666666-6666-6666-6666-666666666666',
        'consent_status' => 'granted',
        'verification_status' => 'healthy',
    ]);

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

    $component = Livewire::actingAs($user)->test(ListProviderConnections::class);
    $table = $component->instance()->getTable();
    $visibleColumnNames = collect($table->getVisibleColumns())
        ->map(fn ($column): string => $column->getName())
        ->values()
        ->all();
    $globalSearchProperty = new ReflectionProperty(ProviderConnectionResource::class, 'isGloballySearchable');
    $globalSearchProperty->setAccessible(true);

    expect($globalSearchProperty->getValue())->toBeFalse()
        ->and(array_keys(ProviderConnectionResource::getPages()))->toContain('view', 'edit')
        ->and($visibleColumnNames)->toContain('provider', 'target_scope', 'consent_status', 'verification_status')
        ->and($visibleColumnNames)->not->toContain('entra_tenant_id');

    $this->actingAs($user)
        ->get(ProviderConnectionResource::getUrl('view', [
            'record' => $connection,
            'managed_environment_id' => $tenant->external_id,
        ], panel: 'admin'))
        ->assertOk()
        ->assertSee('Target scope')
        ->assertSee('Provider context')
        ->assertSee('Microsoft tenant ID')
        ->assertDontSee('Entra tenant ID');
});
