<?php

use App\Filament\Pages\TenantDiagnostics;
use App\Models\TenantMembership;
use App\Support\Rbac\UiTooltips;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('allows members to access the tenant diagnostics page', function () {
    [$user, $tenant] = createUserWithTenant(role: 'readonly');

    $this->actingAs($user)
        ->get("/admin/t/{$tenant->external_id}/diagnostics")
        ->assertSuccessful();
});

it('returns 404 for non-members on the tenant diagnostics page', function () {
    $tenant = Tenant::factory()->create(['external_id' => 'tenant-diag-a']);
    $user = User::factory()->create();

    $this->actingAs($user)
        ->get("/admin/t/{$tenant->external_id}/diagnostics")
        ->assertNotFound();
});

it('shows disabled repair affordances to readonly members when a defect exists', function () {
    [$user, $tenant] = createUserWithTenant(role: 'readonly');

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

    TenantMembership::query()
        ->where('tenant_id', (int) $tenant->getKey())
        ->update(['role' => 'readonly']);

    Livewire::test(TenantDiagnostics::class)
        ->assertActionVisible('bootstrapOwner')
        ->assertActionDisabled('bootstrapOwner')
        ->assertActionExists('bootstrapOwner', function (Action $action): bool {
            return $action->getTooltip() === UiTooltips::INSUFFICIENT_PERMISSION;
        });
});
