<?php

declare(strict_types=1);

use App\Filament\Pages\Monitoring\AuditLog as AuditLogPage;
use App\Models\AuditLog;
use App\Models\OperationRun;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Livewire\Livewire;

it('hydrates the selected audit event from the query and renders inline detail', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $audit = AuditLog::query()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'actor_email' => 'owner@example.com',
        'actor_name' => 'Owner',
        'actor_type' => 'human',
        'action' => 'workspace.selected',
        'status' => 'success',
        'resource_type' => 'workspace',
        'resource_id' => (string) $tenant->workspace_id,
        'target_label' => 'Workspace 1',
        'summary' => 'Workspace selected for Workspace 1',
        'metadata' => [
            'reason' => 'chooser',
            'method' => 'manual',
        ],
        'recorded_at' => now(),
    ]);

    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
    Filament::setTenant(null, true);

    Livewire::withQueryParams([
        'event' => (int) $audit->getKey(),
    ])
        ->actingAs($user)
        ->test(AuditLogPage::class)
        ->assertCanSeeTableRecords([$audit])
        ->assertSet('selectedAuditLogId', (int) $audit->getKey())
        ->assertSee('Workspace selected for Workspace 1')
        ->assertSee('Readable context')
        ->assertSee('Technical metadata')
        ->assertActionVisible('close_selected_audit_event');
});

it('shows related navigation only for the currently selected operation-run event', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

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

    $withRunLink = AuditLog::query()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'actor_email' => 'owner@example.com',
        'actor_name' => 'Owner',
        'actor_type' => 'human',
        'action' => 'operation_run.completed',
        'status' => 'success',
        'resource_type' => 'operation_run',
        'resource_id' => (string) $run->getKey(),
        'target_label' => 'Baseline compare #'.$run->getKey(),
        'summary' => 'Baseline compare completed for Operation run',
        'recorded_at' => now(),
    ]);

    $withoutRunLink = AuditLog::query()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => null,
        'actor_email' => 'owner@example.com',
        'actor_name' => 'Owner',
        'actor_type' => 'human',
        'action' => 'workspace.selected',
        'status' => 'success',
        'resource_type' => 'workspace',
        'resource_id' => (string) $tenant->workspace_id,
        'target_label' => 'Workspace 1',
        'summary' => 'Workspace selected for Workspace 1',
        'recorded_at' => now()->addSecond(),
    ]);

    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
    Filament::setTenant(null, true);

    Livewire::withQueryParams([
        'event' => (int) $withRunLink->getKey(),
    ])
        ->actingAs($user)
        ->test(AuditLogPage::class)
        ->assertCanSeeTableRecords([$withRunLink, $withoutRunLink])
        ->assertActionVisible('open_selected_audit_target');

    Livewire::withQueryParams([
        'event' => (int) $withoutRunLink->getKey(),
    ])
        ->actingAs($user)
        ->test(AuditLogPage::class)
        ->assertSee('Workspace selected for Workspace 1')
        ->assertActionDoesNotExist('open_selected_audit_target');
});

it('falls back to the unselected history when the requested event is invalid or unavailable', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $audit = AuditLog::query()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'actor_email' => 'owner@example.com',
        'actor_name' => 'Owner',
        'actor_type' => 'human',
        'action' => 'workspace.selected',
        'status' => 'success',
        'resource_type' => 'workspace',
        'resource_id' => (string) $tenant->workspace_id,
        'target_label' => 'Workspace 1',
        'summary' => 'Workspace selected for Workspace 1',
        'recorded_at' => now(),
    ]);

    $foreignTenant = \App\Models\ManagedEnvironment::factory()->create();

    $foreignAudit = AuditLog::query()->create([
        'workspace_id' => (int) $foreignTenant->workspace_id,
        'managed_environment_id' => (int) $foreignTenant->getKey(),
        'actor_email' => 'owner@example.com',
        'actor_name' => 'Owner',
        'actor_type' => 'human',
        'action' => 'workspace.selected',
        'status' => 'success',
        'resource_type' => 'workspace',
        'resource_id' => (string) $foreignTenant->workspace_id,
        'target_label' => 'Workspace 2',
        'summary' => 'Foreign workspace selected',
        'recorded_at' => now()->addSecond(),
    ]);

    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
    Filament::setTenant(null, true);

    Livewire::withQueryParams(['event' => 999999])
        ->actingAs($user)
        ->test(AuditLogPage::class)
        ->assertSet('selectedAuditLogId', null)
        ->assertActionDoesNotExist('close_selected_audit_event');

    Livewire::withQueryParams(['event' => (int) $foreignAudit->getKey()])
        ->actingAs($user)
        ->test(AuditLogPage::class)
        ->assertSet('selectedAuditLogId', null)
        ->assertActionDoesNotExist('close_selected_audit_event');
});

it('keeps selected-event actions out of the page header until an event is selected', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

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

    $audit = AuditLog::query()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'actor_email' => 'owner@example.com',
        'actor_name' => 'Owner',
        'actor_type' => 'human',
        'action' => 'operation_run.completed',
        'status' => 'success',
        'resource_type' => 'operation_run',
        'resource_id' => (string) $run->getKey(),
        'target_label' => 'Baseline compare #'.$run->getKey(),
        'summary' => 'Baseline compare completed for Operation run',
        'recorded_at' => now(),
    ]);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(route('admin.monitoring.audit-log'))
        ->assertOk()
        ->assertDontSee('Close details')
        ->assertDontSee('Open operation');

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(route('admin.monitoring.audit-log', ['event' => (int) $audit->getKey()]))
        ->assertOk()
        ->assertSee('Close details')
        ->assertSee('Open operation');
});

it('surfaces origin context quietly when deep-linked to a selected audit event', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $audit = AuditLog::query()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'actor_email' => 'owner@example.com',
        'actor_name' => 'Owner',
        'actor_type' => 'human',
        'action' => 'workspace.selected',
        'status' => 'success',
        'resource_type' => 'workspace',
        'resource_id' => (string) $tenant->workspace_id,
        'target_label' => 'Workspace 1',
        'summary' => 'Workspace selected for Workspace 1',
        'recorded_at' => now(),
    ]);

    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
    Filament::setTenant(null, true);

    Livewire::withQueryParams([
        'event' => (int) $audit->getKey(),
        'nav' => [
            'source_surface' => 'alerts.overview',
            'canonical_route_name' => 'admin.monitoring.audit-log',
            'back_label' => 'Back to alerts',
            'back_url' => '/admin/alerts',
        ],
    ])
        ->actingAs($user)
        ->test(AuditLogPage::class)
        ->assertSet('selectedAuditLogId', (int) $audit->getKey())
        ->assertActionVisible('operate_hub_back_to_origin_audit_log');
});
