<?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('adds provider capability summary to provider connection list and detail surfaces', 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 283 capability connection',
        'entra_tenant_id' => (string) $tenant->managed_environment_id,
        'provider' => 'microsoft',
        'verification_status' => 'healthy',
    ]);

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

    $component = Livewire::actingAs($user)->test(ListProviderConnections::class);
    $visibleColumnNames = collect($component->instance()->getTable()->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_capability');

    $this->actingAs($user)
        ->get(ProviderConnectionResource::getUrl('view', [
            'record' => $connection,
            'managed_environment_id' => $tenant->external_id,
        ], panel: 'admin'))
        ->assertOk()
        ->assertSee('Provider capability')
        ->assertSee('Provider connection check');
});
