<?php

declare(strict_types=1);

use App\Models\ManagedEnvironment;
use App\Support\Filament\CanonicalAdminEnvironmentFilterState;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;

uses(RefreshDatabase::class);

function canonicalAdminEnvironmentRequest(): Request
{
    $request = Request::create('/admin/non-hub-test');
    $request->setLaravelSession(app('session.store'));

    return $request;
}

it('clears tenant-sensitive persisted filters when the canonical admin tenant changes', function (): void {
    $tenantA = ManagedEnvironment::factory()->create();
    [$user, $tenantA] = createUserWithTenant(tenant: $tenantA, role: 'owner');

    $tenantB = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $tenantA->workspace_id,
    ]);

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

    $this->actingAs($user);
    Filament::setTenant(null, true);

    $workspaceId = (int) $tenantA->workspace_id;
    $filtersSessionKey = 'filament.test.filters';

    session()->put(WorkspaceContext::SESSION_KEY, $workspaceId);
    session()->put(WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY, [
        (string) $workspaceId => (int) $tenantA->getKey(),
    ]);
    session()->put($filtersSessionKey, [
        'run_ids' => ['baseline_operation_run_id' => 101],
        'status' => ['value' => 'new'],
    ]);

    app(CanonicalAdminEnvironmentFilterState::class)->sync(
        $filtersSessionKey,
        ['run_ids'],
        canonicalAdminEnvironmentRequest(),
        null,
    );

    session()->put(WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY, [
        (string) $workspaceId => (int) $tenantB->getKey(),
    ]);

    app(CanonicalAdminEnvironmentFilterState::class)->sync(
        $filtersSessionKey,
        ['run_ids'],
        canonicalAdminEnvironmentRequest(),
        null,
    );

    expect(session()->get($filtersSessionKey))
        ->toMatchArray([
            'status' => ['value' => 'new'],
        ])
        ->not->toHaveKey('run_ids');
});

it('can seed a non-default tenant filter with the canonical tenant external id', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $this->actingAs($user);
    Filament::setTenant(null, true);

    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
    session()->put(WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY, [
        (string) $tenant->workspace_id => (int) $tenant->getKey(),
    ]);

    app(CanonicalAdminEnvironmentFilterState::class)->sync(
        'filament.provider.filters',
        request: canonicalAdminEnvironmentRequest(),
        environmentFilterName: 'tenant',
        environmentAttribute: 'external_id',
    );

    expect(session()->get('filament.provider.filters'))
        ->toMatchArray([
            'tenant' => ['value' => (string) $tenant->external_id],
        ]);
});

it('preserves existing non-tenant filters when canonical tenant state seeds a tenant filter', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $this->actingAs($user);
    Filament::setTenant(null, true);

    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
    session()->put(WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY, [
        (string) $tenant->workspace_id => (int) $tenant->getKey(),
    ]);
    session()->put('filament.provider.filters', [
        'status' => ['value' => 'active'],
    ]);

    app(CanonicalAdminEnvironmentFilterState::class)->sync(
        'filament.provider.filters',
        request: canonicalAdminEnvironmentRequest(),
        environmentFilterName: 'tenant',
        environmentAttribute: 'external_id',
    );

    expect(session()->get('filament.provider.filters'))
        ->toMatchArray([
            'status' => ['value' => 'active'],
            'tenant' => ['value' => (string) $tenant->external_id],
        ]);
});

it('does not persist an empty filter bag when only canonical tenant state is synced', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $this->actingAs($user);
    Filament::setTenant(null, true);

    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
    session()->put(WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY, [
        (string) $tenant->workspace_id => (int) $tenant->getKey(),
    ]);

    app(CanonicalAdminEnvironmentFilterState::class)->sync(
        'filament.findings.filters',
        request: canonicalAdminEnvironmentRequest(),
        environmentFilterName: null,
    );

    expect(session()->has('filament.findings.filters'))->toBeFalse();
});
