<?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\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OperationRunType;
use App\Support\Providers\ProviderReasonCodes;
use App\Support\Providers\ProviderVerificationStatus;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Livewire\Livewire;

function productKnowledgeTenantSupportDiagnosticsComponent(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 productKnowledgeOperationSupportDiagnosticsComponent(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]);
}

/**
 * @return array{0: User, 1: ManagedEnvironment, 2: OperationRun}
 */
function createProductKnowledgeSupportDiagnosticScenario(string $state): array
{
    $tenant = ManagedEnvironment::factory()->create(['name' => 'Contoso Support ManagedEnvironment']);
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'operator');

    $reasonCode = match ($state) {
        'admin_consent' => ProviderReasonCodes::ProviderConsentMissing,
        'required_permissions' => ProviderReasonCodes::ProviderPermissionMissing,
        'connection_unhealthy' => ProviderReasonCodes::ProviderAuthFailed,
        'retryable_provider_failure' => ProviderReasonCodes::RateLimited,
        'manual_handoff_required' => ProviderReasonCodes::UnknownError,
        default => null,
    };

    $connection = $reasonCode !== null
        ? ProviderConnection::factory()->withCredential()->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'workspace_id' => (int) $tenant->workspace_id,
            'display_name' => 'Contoso Microsoft connection',
            'verification_status' => $reasonCode === ProviderReasonCodes::UnknownError
                ? ProviderVerificationStatus::Blocked->value
                : ProviderVerificationStatus::Healthy->value,
            'last_error_reason_code' => $reasonCode,
            'last_health_check_at' => now()->subMinutes(15),
        ])
        : null;

    $runOutcome = match ($state) {
        'verification_failed', 'manual_handoff_required' => OperationRunOutcome::Failed->value,
        default => OperationRunOutcome::Succeeded->value,
    };

    $failureSummary = match ($state) {
        'verification_failed' => [[
            'message' => 'The operation failed and needs follow-up.',
        ]],
        'manual_handoff_required' => [[
            'message' => 'A human support handoff is required for the next step.',
            'reason_code' => ProviderReasonCodes::UnknownError,
        ]],
        default => [],
    };

    $context = [];

    if ($connection instanceof ProviderConnection) {
        $context['provider_connection_id'] = (int) $connection->getKey();
    }

    $run = OperationRun::factory()
        ->forTenant($tenant)
        ->create([
            'type' => OperationRunType::BaselineCompare->value,
            'status' => OperationRunStatus::Completed->value,
            'outcome' => $runOutcome,
            'summary_counts' => [
                'total' => 0,
                'processed' => 0,
            ],
            'context' => $context,
            'failure_summary' => $failureSummary,
            'completed_at' => now()->subMinutes(10),
        ]);

    return [$user, $tenant, $run];
}

it('renders shared product knowledge in tenant support diagnostics', function (
    string $state,
    string $headline,
    string $safeNextAction,
    ?string $linkLabel,
): void {
    [$user, $tenant] = createProductKnowledgeSupportDiagnosticScenario($state);

    $component = productKnowledgeTenantSupportDiagnosticsComponent($user, $tenant);

    $component->mountAction('openSupportDiagnostics')
        ->assertMountedActionModalSee('Contextual help')
        ->assertMountedActionModalSee($headline)
        ->assertMountedActionModalSee($safeNextAction);

    if ($linkLabel !== null) {
        $component->assertMountedActionModalSee($linkLabel);
    }
})->with([
    'tenant admin consent required' => ['admin_consent', 'Admin consent required', 'Grant admin consent and re-run verification.', 'Grant admin consent'],
    'tenant required permissions missing' => ['required_permissions', 'Required permissions missing', 'Open required permissions and confirm the missing grants.', 'Open required permissions'],
    'tenant connection unhealthy' => ['connection_unhealthy', 'Provider connection needs review', 'Review the provider connection before retrying.', null],
    'tenant verification failed' => ['verification_failed', 'Verification failed', 'Review the blocking reason and retry verification.', null],
    'tenant diagnostic evidence incomplete' => ['diagnostic_evidence_incomplete', 'Diagnostic evidence is incomplete', 'Collect a fresher or more complete diagnostic signal.', null],
    'tenant retryable provider failure' => ['retryable_provider_failure', 'Provider failure looks retryable', 'Retry after the provider dependency recovers.', null],
    'tenant manual handoff required' => ['manual_handoff_required', 'Manual support handoff required', 'Hand off the case with the current diagnostic summary and supporting references.', null],
]);

it('renders shared product knowledge in operation support diagnostics', function (
    string $state,
    string $headline,
    string $safeNextAction,
    ?string $linkLabel,
): void {
    [$user, , $run] = createProductKnowledgeSupportDiagnosticScenario($state);

    $component = productKnowledgeOperationSupportDiagnosticsComponent($user, $run);

    $component->mountAction('openSupportDiagnostics')
        ->assertMountedActionModalSee('Contextual help')
        ->assertMountedActionModalSee($headline)
        ->assertMountedActionModalSee($safeNextAction);

    if ($linkLabel !== null) {
        $component->assertMountedActionModalSee($linkLabel);
    }
})->with([
    'operation admin consent required' => ['admin_consent', 'Admin consent required', 'Grant admin consent and re-run verification.', 'Grant admin consent'],
    'operation required permissions missing' => ['required_permissions', 'Required permissions missing', 'Open required permissions and confirm the missing grants.', 'Open required permissions'],
    'operation connection unhealthy' => ['connection_unhealthy', 'Provider connection needs review', 'Review the provider connection before retrying.', null],
    'operation verification failed' => ['verification_failed', 'Verification failed', 'Review the blocking reason and retry verification.', null],
    'operation diagnostic evidence incomplete' => ['diagnostic_evidence_incomplete', 'Diagnostic evidence is incomplete', 'Collect a fresher or more complete diagnostic signal.', null],
    'operation retryable provider failure' => ['retryable_provider_failure', 'Provider failure looks retryable', 'Retry after the provider dependency recovers.', null],
    'operation manual handoff required' => ['manual_handoff_required', 'Manual support handoff required', 'Hand off the case with the current diagnostic summary and supporting references.', null],
]);
