<?php

use App\Filament\Resources\PolicyResource\Pages\ListPolicies;
use App\Models\Policy;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\App;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('filters active, ignored, and provider-missing policy states distinctly', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);

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

    $active = Policy::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'display_name' => 'Active policy',
        'ignored_at' => null,
        'missing_from_provider_at' => null,
    ]);

    $missing = Policy::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'display_name' => 'Provider missing policy',
        'ignored_at' => null,
        'missing_from_provider_at' => now()->subHour(),
    ]);

    $combined = Policy::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'display_name' => 'Ignored missing policy',
        'ignored_at' => now()->subDay(),
        'missing_from_provider_at' => now()->subHour(),
    ]);

    Livewire::actingAs($user)
        ->test(ListPolicies::class)
        ->assertCanSeeTableRecords([$active])
        ->assertCanNotSeeTableRecords([$missing, $combined])
        ->set('tableFilters.visibility.value', 'provider_missing')
        ->assertCanSeeTableRecords([$missing, $combined])
        ->assertCanNotSeeTableRecords([$active])
        ->set('tableFilters.visibility.value', 'ignored')
        ->assertCanSeeTableRecords([$combined])
        ->assertCanNotSeeTableRecords([$active, $missing]);
});

it('keeps provider-missing sync retry available and current export disabled', function (): void {
    App::setLocale('en');

    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);

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

    $policy = Policy::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'display_name' => 'Provider missing policy',
        'ignored_at' => null,
        'missing_from_provider_at' => now()->subHour(),
    ]);

    Livewire::actingAs($user)
        ->test(ListPolicies::class)
        ->set('tableFilters.visibility.value', 'provider_missing')
        ->assertCanSeeTableRecords([$policy])
        ->assertSee(__('localization.policy.badges.source_unavailable'))
        ->assertTableActionEnabled('sync', $policy)
        ->assertTableActionDisabled('export', $policy);
});
