<?php

declare(strict_types=1);

use App\Filament\Resources\EnvironmentReviewResource;
use App\Filament\Resources\EnvironmentReviewResource\Pages\ListEnvironmentReviews;
use App\Filament\Resources\EnvironmentReviewResource\Pages\ViewEnvironmentReview;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Support\Auth\UiTooltips;
use Livewire\Livewire;

it('returns not found for non-members on the environment review library and detail routes', function (): void {
    $targetTenant = ManagedEnvironment::factory()->create();
    [$member] = createUserWithTenant(role: 'owner');
    $reviewOwner = User::factory()->create();
    createUserWithTenant(tenant: $targetTenant, user: $reviewOwner, role: 'owner');
    $review = composeEnvironmentReviewForTest($targetTenant, $reviewOwner);

    $this->actingAs($member)
        ->get(EnvironmentReviewResource::environmentScopedUrl('index', tenant: $targetTenant))
        ->assertNotFound();

    $this->actingAs($member)
        ->get(EnvironmentReviewResource::environmentScopedUrl('view', ['record' => $review], $targetTenant))
        ->assertNotFound();
});

it('allows readonly members to inspect reviews but keeps create actions disabled', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$owner, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');
    [$readonly] = createUserWithTenant(tenant: $tenant, user: User::factory()->create(), role: 'readonly');
    $review = composeEnvironmentReviewForTest($tenant, $owner);

    $this->actingAs($readonly)
        ->get(EnvironmentReviewResource::environmentScopedUrl('view', ['record' => $review], $tenant))
        ->assertOk();

    setAdminEnvironmentContext($tenant);

    Livewire::actingAs($readonly)
        ->test(ListEnvironmentReviews::class)
        ->assertActionVisible('create_review')
        ->assertActionDisabled('create_review')
        ->assertActionExists('create_review', fn ($action): bool => $action->getTooltip() === UiTooltips::insufficientPermission());

    Livewire::actingAs($readonly)
        ->test(ViewEnvironmentReview::class, ['record' => $review->getKey()])
        ->assertActionVisible('publish_review')
        ->assertActionDisabled('publish_review')
        ->assertActionVisible('archive_review')
        ->assertActionDisabled('archive_review');
});
