<?php

declare(strict_types=1);

use App\Models\OperationRun;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

final class OperationsListTenantlessSafetyTest extends TestCase
{
    use RefreshDatabase;

    public function test_renders_workspace_operations_list_with_tenantless_runs_when_no_tenant_context_is_set(): void
    {
        [$user, $tenant] = createUserWithTenant(role: 'owner');

        OperationRun::factory()->create([
            'workspace_id' => (int) $tenant->workspace_id,
            'managed_environment_id' => null,
            'type' => 'provider.connection.check',
            'initiator_name' => 'Tenantless run',
            'status' => 'queued',
            'outcome' => 'pending',
        ]);

        OperationRun::factory()->create([
            'workspace_id' => (int) $tenant->workspace_id,
            'managed_environment_id' => (int) $tenant->getKey(),
            'type' => 'policy.sync',
            'initiator_name' => 'ManagedEnvironment run',
            'status' => 'queued',
            'outcome' => 'pending',
        ]);

        Filament::setTenant(null, true);

        $this->actingAs($user)
            ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
            ->get(\App\Support\OperationRunLinks::index())
            ->assertOk()
            ->assertSee('Tenantless run')
            ->assertSee('ManagedEnvironment run');
    }

    public function test_renders_workspace_operations_list_workspace_wide_even_with_tenant_context_and_tenantless_records_present(): void
    {
        [$user, $tenant] = createUserWithTenant(role: 'owner');

        OperationRun::factory()->create([
            'workspace_id' => (int) $tenant->workspace_id,
            'managed_environment_id' => null,
            'type' => 'provider.connection.check',
            'initiator_name' => 'Tenantless run',
            'status' => 'queued',
            'outcome' => 'pending',
        ]);

        OperationRun::factory()->create([
            'workspace_id' => (int) $tenant->workspace_id,
            'managed_environment_id' => (int) $tenant->getKey(),
            'type' => 'policy.sync',
            'initiator_name' => 'ManagedEnvironment run',
            'status' => 'queued',
            'outcome' => 'pending',
        ]);

        Filament::setTenant($tenant, true);

        $this->actingAs($user)
            ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
            ->get(\App\Support\OperationRunLinks::index())
            ->assertOk()
            ->assertSee('ManagedEnvironment run')
            ->assertSee('Tenantless run');
    }
}
