<?php

declare(strict_types=1);

use App\Filament\Pages\Operations\TenantlessOperationRunViewer;
use App\Filament\Pages\TenantDashboard;
use App\Models\OperationRun;
use App\Models\Tenant;
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 supportDiagnosticsTenantAuthorizationComponent(User $user, Tenant $tenant): \Livewire\Features\SupportTesting\Testable
{
    test()->actingAs($user);
    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
    setTenantPanelContext($tenant);

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

function supportDiagnosticsOperationAuthorizationComponent(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 deny-as-not-found for workspace members without tenant entitlement', function (): void {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create();

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

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

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

    supportDiagnosticsTenantAuthorizationComponent($user, $tenant)
        ->assertActionVisible('openSupportDiagnostics')
        ->assertActionDisabled('openSupportDiagnostics')
        ->call('tenantSupportDiagnosticBundle')
        ->assertForbidden();
});

it('keeps operation-run support diagnostics deny-as-not-found for workspace members without tenant entitlement', function (): void {
    $workspace = Workspace::factory()->create();
    $tenant = Tenant::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',
    ]);

    $run = OperationRun::factory()->create([
        'tenant_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(route('admin.operations.view', ['run' => (int) $run->getKey()]))
        ->assertNotFound();
});

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

    $run = OperationRun::factory()->create([
        'tenant_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(),
    ]);

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