<?php

declare(strict_types=1);

use App\Models\Tenant;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('shows only active tenants and no-tenant helper copy on the choose-tenant page', function (): void {
    $activeTenant = Tenant::factory()->active()->create(['name' => 'Choose Active Tenant']);
    [$user, $activeTenant] = createUserWithTenant(tenant: $activeTenant, role: 'owner');

    $otherActiveTenant = Tenant::factory()->active()->create([
        'workspace_id' => (int) $activeTenant->workspace_id,
        'name' => 'Choose Other Active Tenant',
    ]);
    $onboardingTenant = Tenant::factory()->onboarding()->create([
        'workspace_id' => (int) $activeTenant->workspace_id,
        'name' => 'Choose Onboarding Tenant',
    ]);
    $archivedTenant = Tenant::factory()->archived()->create([
        'workspace_id' => (int) $activeTenant->workspace_id,
        'name' => 'Choose Archived Tenant',
    ]);

    createUserWithTenant(tenant: $otherActiveTenant, user: $user, role: 'owner');
    createUserWithTenant(tenant: $onboardingTenant, user: $user, role: 'owner', ensureDefaultMicrosoftProviderConnection: false);
    createUserWithTenant(tenant: $archivedTenant, user: $user, role: 'owner', ensureDefaultMicrosoftProviderConnection: false);

    Filament::setTenant(null, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $activeTenant->workspace_id])
        ->get('/admin/choose-tenant')
        ->assertSuccessful()
        ->assertSee('Choose Active Tenant')
        ->assertSee('Choose Other Active Tenant')
        ->assertDontSee('Choose Onboarding Tenant')
        ->assertDontSee('Choose Archived Tenant')
        ->assertSee('Select the tenant for your normal active operating context.')
        ->assertSee('No tenant selected is still a valid workspace state');
});

it('shows a workspace-safe empty state when no selectable tenants remain', function (): void {
    $onboardingTenant = Tenant::factory()->onboarding()->create(['name' => 'Only Onboarding Tenant']);
    [$user, $onboardingTenant] = createUserWithTenant(
        tenant: $onboardingTenant,
        role: 'owner',
        ensureDefaultMicrosoftProviderConnection: false,
    );

    Filament::setTenant(null, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $onboardingTenant->workspace_id])
        ->get('/admin/choose-tenant')
        ->assertSuccessful()
        ->assertSee('No active tenants available')
        ->assertSee('Workspace-level pages still work with no tenant selected')
        ->assertSee('View managed tenants');
});

it('keeps selector eligibility narrower than managed-tenant administrative discoverability', function (): void {
    $activeTenant = Tenant::factory()->active()->create(['name' => 'Selector Active Tenant']);
    [$user, $activeTenant] = createUserWithTenant(tenant: $activeTenant, role: 'owner', ensureDefaultMicrosoftProviderConnection: false);

    $onboardingTenant = Tenant::factory()->onboarding()->create([
        'workspace_id' => (int) $activeTenant->workspace_id,
        'name' => 'Selector Onboarding Tenant',
    ]);
    $archivedTenant = Tenant::factory()->archived()->create([
        'workspace_id' => (int) $activeTenant->workspace_id,
        'name' => 'Selector Archived Tenant',
    ]);

    createUserWithTenant(tenant: $onboardingTenant, user: $user, role: 'owner', workspaceRole: 'owner', ensureDefaultMicrosoftProviderConnection: false);
    createUserWithTenant(tenant: $archivedTenant, user: $user, role: 'owner', workspaceRole: 'owner', ensureDefaultMicrosoftProviderConnection: false);

    Filament::setTenant(null, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $activeTenant->workspace_id])
        ->get('/admin/choose-tenant')
        ->assertSuccessful()
        ->assertSee('Selector Active Tenant')
        ->assertDontSee('Selector Onboarding Tenant')
        ->assertDontSee('Selector Archived Tenant');

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $activeTenant->workspace_id])
        ->get(route('admin.workspace.managed-tenants.index', ['workspace' => $activeTenant->workspace]))
        ->assertSuccessful()
        ->assertSee('Selector Active Tenant')
        ->assertSee('Selector Onboarding Tenant')
        ->assertSee('Selector Archived Tenant');
});

it('redirects clear selected tenant from tenant-bound pages back to a workspace-safe managed-tenants page', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    Filament::setTenant($tenant, true);

    $this->actingAs($user)
        ->withSession([
            WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id,
            WorkspaceContext::LAST_TENANT_IDS_SESSION_KEY => [
                (string) $tenant->workspace_id => (int) $tenant->getKey(),
            ],
        ])
        ->from("/admin/tenants/{$tenant->external_id}")
        ->post(route('admin.clear-tenant-context'))
        ->assertRedirect(route('admin.workspace.managed-tenants.index', ['workspace' => $tenant->workspace]));

    $this->withSession([
        WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id,
    ])->get(route('admin.operations.index'))
        ->assertSuccessful()
        ->assertSee('All tenants');
});

it('redirects clear selected tenant from the evidence index to the workspace-safe evidence overview', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    Filament::setTenant($tenant, true);

    $this->actingAs($user)
        ->withSession([
            WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id,
            WorkspaceContext::LAST_TENANT_IDS_SESSION_KEY => [
                (string) $tenant->workspace_id => (int) $tenant->getKey(),
            ],
        ])
        ->from('/admin/evidence')
        ->post(route('admin.clear-tenant-context'))
        ->assertRedirect(route('admin.evidence.overview'));

    $this->withSession([
        WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id,
    ])->get(route('admin.evidence.overview'))
        ->assertSuccessful()
        ->assertSee('No evidence snapshots in this scope');
});
