<?php

use App\Filament\Resources\ManagedEnvironmentResource\Pages\ViewManagedEnvironment;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

test('rbac card shows not configured hint when rbac_status is null', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $tenant->update([
        'rbac_status' => null,
        'rbac_last_checked_at' => null,
    ]);

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

    Livewire::test(ViewManagedEnvironment::class, ['record' => $tenant->getRouteKey()])
        ->assertSee('Not configured');
});

test('rbac card shows healthy summary when rbac_status is ok and fresh', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $tenant->update([
        'rbac_status' => 'ok',
        'rbac_last_checked_at' => now()->subMinutes(5),
    ]);

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

    Livewire::test(ViewManagedEnvironment::class, ['record' => $tenant->getRouteKey()])
        ->assertSee('healthy and up to date');
});

test('rbac card shows unhealthy summary for degraded status', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $tenant->update([
        'rbac_status' => 'degraded',
        'rbac_last_checked_at' => now(),
    ]);

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

    Livewire::test(ViewManagedEnvironment::class, ['record' => $tenant->getRouteKey()])
        ->assertSee('unhealthy state');
});

test('refresh rbac header action exists on ViewTenant', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

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

    Livewire::test(ViewManagedEnvironment::class, ['record' => $tenant->getRouteKey()])
        ->assertActionExists('refresh_rbac');
});
