<?php

declare(strict_types=1);

use App\Models\ManagedEnvironment;
use App\Models\OperationRun;
use App\Models\PlatformUser;
use App\Models\User;
use App\Models\Workspace;
use App\Support\Auth\PlatformCapabilities;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OperationRunType;
use App\Support\System\SystemOperationRunLinks;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

beforeEach(function (): void {
    Filament::setCurrentPanel('system');
    Filament::bootCurrentPanel();
});

it('keeps canonical run detail readable for closed workspaces and removed tenants', function (): void {
    $platformUser = PlatformUser::factory()->create([
        'capabilities' => [
            PlatformCapabilities::ACCESS_SYSTEM_PANEL,
            PlatformCapabilities::OPERATIONS_VIEW,
        ],
        'is_active' => true,
    ]);

    $workspace = Workspace::factory()->create([
        'name' => 'Historical Closure Workspace',
        'closed_at' => now(),
        'closed_by_platform_user_id' => (int) $platformUser->getKey(),
        'closed_reason' => 'Historical closure for support verification.',
    ]);

    $tenantUser = User::factory()->create();
    $tenant = ManagedEnvironment::factory()->active()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'name' => 'Removed Historical ManagedEnvironment',
        'removed_from_workspace_at' => now(),
        'removed_from_workspace_by_user_id' => (int) $tenantUser->getKey(),
        'removed_from_workspace_reason' => 'Tenant was offboarded from the workspace.',
    ]);

    $run = OperationRun::factory()
        ->forTenant($tenant)
        ->create([
            'type' => OperationRunType::InventorySync->value,
            'status' => OperationRunStatus::Completed->value,
            'outcome' => OperationRunOutcome::Succeeded->value,
            'started_at' => now()->subMinutes(3),
            'completed_at' => now(),
        ]);

    $this->actingAs($platformUser, 'platform')
        ->get(SystemOperationRunLinks::view($run))
        ->assertSuccessful()
        ->assertSee('Historical Closure Workspace')
        ->assertSee('Removed Historical ManagedEnvironment')
        ->assertSee('Workspace lifecycle')
        ->assertSee('Closed')
        ->assertSee('Tenant workspace posture')
        ->assertSee('Removed from workspace');
});
