<?php

declare(strict_types=1);

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

function productKnowledgeSupportDiagnosticsTenantAuthorizationComponent(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 productKnowledgeSupportDiagnosticsOperationAuthorizationComponent(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('keeps tenant support diagnostics contextual help deny-as-not-found for workspace members without tenant entitlement', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    $user = User::factory()->create();

    WorkspaceMembership::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'user_id' => (int) $user->getKey(),
        'role' => 'operator',
    ]);
    createUserWithTenant(
        tenant: ManagedEnvironment::factory()->create(['workspace_id' => (int) $tenant->workspace_id]),
        user: $user,
        role: 'operator',
    );

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(EnvironmentDashboard::getUrl(panel: 'admin', tenant: $tenant))
        ->assertNotFound();
});

it('returns forbidden for entitled run viewers without support diagnostics capability when requesting the contextual-help bundle', 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,
        'completed_at' => now(),
    ]);

    productKnowledgeSupportDiagnosticsOperationAuthorizationComponent($user, $run)
        ->assertActionVisible('openSupportDiagnostics')
        ->assertActionDisabled('openSupportDiagnostics')
        ->call('operationRunSupportDiagnosticBundle')
        ->assertForbidden();
});

it('omits support diagnostics contextual help when the dominant issue does not map to a catalog topic', function (): void {
    $tenant = ManagedEnvironment::factory()->create(['name' => 'Fallback Support ManagedEnvironment']);
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'operator');

    $connection = ProviderConnection::factory()
        ->withCredential()
        ->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'workspace_id' => (int) $tenant->workspace_id,
            'display_name' => 'Fallback connection',
            'last_error_reason_code' => 'ext.support.manual_lookup_needed',
            'last_health_check_at' => now()->subMinutes(5),
        ]);

    $run = OperationRun::factory()
        ->forTenant($tenant)
        ->create([
            'type' => OperationRunType::BaselineCompare->value,
            'status' => OperationRunStatus::Completed->value,
            'outcome' => OperationRunOutcome::Succeeded->value,
            'context' => [
                'provider_connection_id' => (int) $connection->getKey(),
            ],
            'completed_at' => now()->subMinutes(3),
        ]);

    productKnowledgeSupportDiagnosticsOperationAuthorizationComponent($user, $run)
        ->mountAction('openSupportDiagnostics')
        ->assertMountedActionModalDontSee('Contextual help')
        ->assertMountedActionModalDontSee('ext.support.manual_lookup_needed');
});

it('keeps operation-run support diagnostics deny-as-not-found for workspace members without tenant entitlement', function (): void {
    $workspace = Workspace::factory()->create();
    $tenant = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
    ]);

    $user = User::factory()->create();

    WorkspaceMembership::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'user_id' => (int) $user->getKey(),
        'role' => 'owner',
    ]);
    createUserWithTenant(
        tenant: ManagedEnvironment::factory()->create(['workspace_id' => (int) $workspace->getKey()]),
        user: $user,
        role: 'owner',
    );

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

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()])
        ->get(\App\Support\OperationRunLinks::tenantlessView($run))
        ->assertNotFound();
});
