<?php

declare(strict_types=1);

use App\Filament\Pages\Operations\TenantlessOperationRunViewer;
use App\Filament\Pages\EnvironmentDashboard;
use App\Models\OperationRun;
use App\Models\ProductUsageEvent;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OperationRunType;
use App\Support\ProductTelemetry\ProductUsageEventCatalog;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

function tenantDiagnosticsTelemetryComponent(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 operationDiagnosticsTelemetryComponent(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('records telemetry when support diagnostics are opened from the tenant dashboard', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'operator');

    tenantDiagnosticsTelemetryComponent($user, $tenant)
        ->mountAction('openSupportDiagnostics')
        ->assertMountedActionModalSee('Support diagnostics');

    $event = ProductUsageEvent::query()->sole();
    $serializedEvent = json_encode($event->toArray(), JSON_THROW_ON_ERROR);

    expect($event->event_name)->toBe(ProductUsageEventCatalog::SUPPORT_DIAGNOSTICS_OPENED)
        ->and($event->managed_environment_id)->toBe((int) $tenant->getKey())
        ->and($event->workspace_id)->toBe((int) $tenant->workspace_id)
        ->and($event->user_id)->toBe((int) $user->getKey())
        ->and($event->subject_type)->toBe('tenant')
        ->and($event->subject_id)->toBe((string) $tenant->getKey())
        ->and($event->metadata)->toBe([
            'source_surface' => 'tenant_dashboard',
        ])
        ->and($serializedEvent)->not->toContain('@')
        ->and($serializedEvent)->not->toContain($user->name)
        ->and($serializedEvent)->not->toContain((string) $tenant->name);
});

it('records telemetry when support diagnostics are opened from the canonical operation viewer', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'operator');

    $run = OperationRun::factory()->forTenant($tenant)->create([
        'user_id' => (int) $user->getKey(),
        'initiator_name' => $user->name,
        'type' => OperationRunType::ReviewPackGenerate->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Succeeded->value,
        'completed_at' => now(),
    ]);

    operationDiagnosticsTelemetryComponent($user, $run)
        ->mountAction('openSupportDiagnostics')
        ->assertMountedActionModalSee('Support diagnostics');

    $event = ProductUsageEvent::query()->sole();
    $serializedEvent = json_encode($event->toArray(), JSON_THROW_ON_ERROR);

    expect($event->event_name)->toBe(ProductUsageEventCatalog::SUPPORT_DIAGNOSTICS_OPENED)
        ->and($event->managed_environment_id)->toBe((int) $tenant->getKey())
        ->and($event->workspace_id)->toBe((int) $tenant->workspace_id)
        ->and($event->user_id)->toBe((int) $user->getKey())
        ->and($event->subject_type)->toBe('operation_run')
        ->and($event->subject_id)->toBe((string) $run->getKey())
        ->and($event->metadata)->toBe([
            'source_surface' => 'operation_run_viewer',
            'operation_type' => OperationRunType::ReviewPackGenerate->value,
        ])
        ->and($serializedEvent)->not->toContain('@')
        ->and($serializedEvent)->not->toContain($user->name)
        ->and($serializedEvent)->not->toContain((string) $tenant->name);
});