<?php

declare(strict_types=1);

use App\Models\ManagedEnvironment;
use App\Models\OperationRun;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

final class CanonicalOperationViewerContextMismatchTest extends TestCase
{
    use RefreshDatabase;

    public function test_keeps_canonical_run_viewer_workspace_scoped_when_selected_tenant_differs_from_the_run_tenant(): void
    {
        $runTenant = ManagedEnvironment::factory()->create([
            'name' => 'Run ManagedEnvironment',
            'workspace_id' => null,
        ]);
        [$user, $runTenant] = createUserWithTenant(tenant: $runTenant, role: 'owner');

        $currentTenant = ManagedEnvironment::factory()->create([
            'name' => 'Current ManagedEnvironment',
            'workspace_id' => (int) $runTenant->workspace_id,
        ]);

        createUserWithTenant(tenant: $currentTenant, user: $user, role: 'owner');

        $run = OperationRun::factory()->create([
            'workspace_id' => (int) $runTenant->workspace_id,
            'managed_environment_id' => (int) $runTenant->getKey(),
            'type' => 'policy.sync',
            'status' => OperationRunStatus::Completed->value,
            'outcome' => OperationRunOutcome::Succeeded->value,
        ]);

        setAdminPanelContext($currentTenant);

        $this->actingAs($user)
            ->withSession([WorkspaceContext::SESSION_KEY => (int) $runTenant->workspace_id])
            ->get(\App\Support\OperationRunLinks::tenantlessView($run))
            ->assertOk()
            ->assertSee('Canonical workspace view')
            ->assertDontSee('Current environment context differs from this operation')
            ->assertDontSee('Current environment context: Current ManagedEnvironment.')
            ->assertSee('Operation environment: Run ManagedEnvironment.');
    }

    public function test_frames_tenantless_runs_as_workspace_level_even_when_tenant_context_is_selected(): void
    {
        $selectedTenant = ManagedEnvironment::factory()->create([
            'name' => 'Selected ManagedEnvironment',
        ]);
        [$user, $selectedTenant] = createUserWithTenant(tenant: $selectedTenant, role: 'owner');

        $run = OperationRun::factory()->create([
            'workspace_id' => (int) $selectedTenant->workspace_id,
            'managed_environment_id' => null,
            'type' => 'provider.connection.check',
            'status' => OperationRunStatus::Completed->value,
            'outcome' => OperationRunOutcome::Succeeded->value,
        ]);

        setAdminPanelContext($selectedTenant);

        $this->actingAs($user)
            ->withSession([WorkspaceContext::SESSION_KEY => (int) $selectedTenant->workspace_id])
            ->get(\App\Support\OperationRunLinks::tenantlessView($run))
            ->assertOk()
            ->assertSee('Workspace-level operation')
            ->assertSee('This canonical workspace view is not tied to any environment.')
            ->assertDontSee('This canonical workspace view is not tied to the current environment context (Selected ManagedEnvironment).');
    }

    public function test_keeps_onboarding_tenant_runs_viewable_with_lifecycle_aware_context(): void
    {
        $tenant = ManagedEnvironment::factory()->create([
            'name' => 'Onboarding ManagedEnvironment',
            'status' => ManagedEnvironment::STATUS_ONBOARDING,
        ]);
        [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

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

        setAdminPanelContext();

        $this->actingAs($user)
            ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
            ->get(\App\Support\OperationRunLinks::tenantlessView($run))
            ->assertOk()
            ->assertSee('Operation environment is not available in the current environment selector')
            ->assertSee('Operation environment: Onboarding ManagedEnvironment.')
            ->assertSee('This tenant is currently onboarding')
            ->assertSee('Back to Operations')
            ->assertDontSee('This tenant is currently active')
            ->assertDontSee('← Back to Onboarding ManagedEnvironment');
    }

    public function test_keeps_archived_tenant_runs_viewable_with_lifecycle_aware_context(): void
    {
        $activeEnvironment = ManagedEnvironment::factory()->create([
            'name' => 'Active ManagedEnvironment',
        ]);
        [$user, $activeEnvironment] = createUserWithTenant(tenant: $activeEnvironment, role: 'owner');

        $archivedTenant = ManagedEnvironment::factory()->create([
            'name' => 'Archived ManagedEnvironment',
            'workspace_id' => (int) $activeEnvironment->workspace_id,
            'status' => ManagedEnvironment::STATUS_ACTIVE,
        ]);

        createUserWithTenant(tenant: $archivedTenant, user: $user, role: 'owner');
        $archivedTenant->delete();

        $run = OperationRun::factory()->create([
            'workspace_id' => (int) $activeEnvironment->workspace_id,
            'managed_environment_id' => (int) $archivedTenant->getKey(),
            'type' => 'inventory_sync',
            'status' => OperationRunStatus::Completed->value,
            'outcome' => OperationRunOutcome::Succeeded->value,
        ]);

        setAdminPanelContext();

        $this->actingAs($user)
            ->withSession([WorkspaceContext::SESSION_KEY => (int) $activeEnvironment->workspace_id])
            ->get(\App\Support\OperationRunLinks::tenantlessView($run))
            ->assertOk()
            ->assertSee('Operation environment is not available in the current environment selector')
            ->assertSee('Operation environment: Archived ManagedEnvironment.')
            ->assertSee('This tenant is currently archived')
            ->assertSee('Back to Operations')
            ->assertDontSee('deactivated')
            ->assertDontSee('← Back to Archived ManagedEnvironment');
    }

    public function test_keeps_selector_excluded_draft_tenant_runs_viewable_with_lifecycle_aware_context(): void
    {
        $tenant = ManagedEnvironment::factory()->create([
            'name' => 'Draft ManagedEnvironment',
            'status' => ManagedEnvironment::STATUS_DRAFT,
        ]);
        [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

        $run = OperationRun::factory()->create([
            'workspace_id' => (int) $tenant->workspace_id,
            'managed_environment_id' => (int) $tenant->getKey(),
            'type' => 'policy.sync',
            'status' => OperationRunStatus::Completed->value,
            'outcome' => OperationRunOutcome::Succeeded->value,
        ]);

        setAdminPanelContext();

        $this->actingAs($user)
            ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
            ->get(\App\Support\OperationRunLinks::tenantlessView($run))
            ->assertOk()
            ->assertSee('Operation environment is not available in the current environment selector')
            ->assertSee('Operation environment: Draft ManagedEnvironment.')
            ->assertSee('This tenant is currently draft')
            ->assertDontSee('Resume onboarding');
    }
}
