<?php

declare(strict_types=1);

use App\Filament\Pages\Monitoring\AuditLog as AuditLogPage;
use App\Models\AuditLog;
use App\Models\ManagedEnvironment;
use App\Support\Audit\AuditActionId;
use App\Support\Workspaces\WorkspaceContext;
use Carbon\CarbonImmutable;
use Filament\Facades\Filament;
use Livewire\Livewire;
use Symfony\Component\HttpFoundation\StreamedResponse;

it('filters support-access history to the active workspace only', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $supportAccess = AuditLog::query()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => null,
        'actor_email' => 'support@example.com',
        'actor_name' => 'Support',
        'actor_type' => 'platform',
        'action' => AuditActionId::SupportAccessRequested->value,
        'status' => 'success',
        'resource_type' => 'support_access_grant',
        'resource_id' => '101',
        'target_label' => 'Audit-view support #101',
        'summary' => 'Support access requested for Current workspace',
        'metadata' => ['reason' => 'Current workspace support'],
        'recorded_at' => now(),
    ]);

    $unrelated = AuditLog::query()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => null,
        'action' => 'workspace.selected',
        'status' => 'success',
        'summary' => 'Workspace selected',
        'metadata' => [],
        'recorded_at' => now()->addSecond(),
    ]);

    $foreignTenant = ManagedEnvironment::factory()->create();
    $foreign = AuditLog::query()->create([
        'workspace_id' => (int) $foreignTenant->workspace_id,
        'managed_environment_id' => null,
        'action' => AuditActionId::SupportAccessRequested->value,
        'status' => 'success',
        'summary' => 'Support access requested for Foreign workspace',
        'metadata' => ['reason' => 'Foreign workspace support'],
        'recorded_at' => now()->addSeconds(2),
    ]);

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

    Livewire::withQueryParams(['supportAccess' => true])
        ->actingAs($user)
        ->test(AuditLogPage::class)
        ->assertSet('supportAccessOnly', true)
        ->assertCanSeeTableRecords([$supportAccess])
        ->assertCanNotSeeTableRecords([$unrelated, $foreign])
        ->assertActionVisible('export_support_access_history');
});

it('exports support-access history for the active workspace only', function (): void {
    CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-05-05 12:00:00'));

    [$user, $tenant] = createUserWithTenant(role: 'owner');

    AuditLog::query()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => null,
        'actor_email' => 'support@example.com',
        'actor_name' => 'Support',
        'actor_type' => 'platform',
        'action' => AuditActionId::SupportAccessRequested->value,
        'status' => 'success',
        'resource_type' => 'support_access_grant',
        'resource_id' => '101',
        'target_label' => 'Audit-view support #101',
        'summary' => 'Support access requested for Current workspace',
        'metadata' => ['reason' => 'Current workspace support'],
        'recorded_at' => now(),
    ]);

    AuditLog::query()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => null,
        'action' => 'workspace.selected',
        'status' => 'success',
        'summary' => 'Workspace selected',
        'metadata' => [],
        'recorded_at' => now()->addSecond(),
    ]);

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

    $component = Livewire::withQueryParams(['supportAccess' => true])
        ->actingAs($user)
        ->test(AuditLogPage::class);

    $response = $component->instance()->exportSupportAccessHistory();

    expect($response)->toBeInstanceOf(StreamedResponse::class)
        ->and($response->headers->get('content-type'))->toContain('text/csv');

    ob_start();
    $response->sendContent();
    $csv = (string) ob_get_clean();

    expect($csv)->toContain(AuditActionId::SupportAccessRequested->value)
        ->and($csv)->toContain('Current workspace support')
        ->and($csv)->not->toContain('workspace.selected');

    CarbonImmutable::setTestNow();
});
