<?php

declare(strict_types=1);

use App\Filament\Pages\Operations\TenantlessOperationRunViewer;
use App\Filament\Pages\EnvironmentDashboard;
use App\Models\OperationRun;
use App\Models\SupportRequest;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OperationRunType;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Livewire\Livewire;

uses(\Illuminate\Foundation\Testing\RefreshDatabase::class);

function supportRequestAuthorizationTenantComponent(User $user, ManagedEnvironment $tenant): \Livewire\Features\SupportTesting\Testable
{
    test()->actingAs($user);
    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
    setAdminEnvironmentContext($tenant);

    return Livewire::actingAs($user)->test(EnvironmentDashboard::class);
}

function supportRequestAuthorizationOperationComponent(User $user, OperationRun $run): \Livewire\Features\SupportTesting\Testable
{
    test()->actingAs($user);
    Filament::setTenant(null, true);
    session()->put(WorkspaceContext::SESSION_KEY, (int) $run->workspace_id);

    return Livewire::actingAs($user)->test(TenantlessOperationRunViewer::class, ['run' => $run]);
}

it('returns forbidden for entitled tenant members without support request capability', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'readonly');

    supportRequestAuthorizationTenantComponent($user, $tenant)
        ->assertActionVisible('requestSupport')
        ->assertActionDisabled('requestSupport')
        ->call('authorizeTenantSupportRequest')
        ->assertForbidden();

    expect(SupportRequest::query()->count())->toBe(0);
});

it('returns forbidden for entitled run viewers without support request capability', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'readonly');

    $run = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Succeeded->value,
        'summary_counts' => [
            'total' => 0,
            'processed' => 0,
        ],
        'completed_at' => now(),
    ]);

    supportRequestAuthorizationOperationComponent($user, $run)
        ->assertActionVisible('requestSupport')
        ->assertActionDisabled('requestSupport')
        ->call('authorizeOperationRunSupportRequest')
        ->assertForbidden();

    expect(SupportRequest::query()->count())->toBe(0);
});
