<?php

declare(strict_types=1);

use App\Filament\Pages\InventoryCoverage;
use App\Filament\Resources\BackupSetResource;
use App\Filament\Resources\PolicyResource;
use App\Filament\Resources\PolicyVersionResource;
use App\Models\ManagedEnvironment;
use App\Models\ManagedEnvironmentMembership;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

dataset('admin tenant scoped surface paths', [
    '/admin/policies',
    '/admin/policy-versions',
    '/admin/backup-sets',
    '/admin/inventory',
    '/admin/inventory/inventory-coverage',
]);

it('keeps retired flat tenant-scoped admin surfaces unavailable when no tenant is selected', function (): void {
    $user = User::factory()->create();

    $workspace = Workspace::factory()->create();

    WorkspaceMembership::factory()->create([
        'workspace_id' => $workspace->getKey(),
        'user_id' => $user->getKey(),
        'role' => 'owner',
    ]);

    $tenants = ManagedEnvironment::factory()->count(2)->create([
        'status' => 'active',
        'workspace_id' => $workspace->getKey(),
    ]);

    foreach ($tenants as $tenant) {
        ManagedEnvironmentMembership::query()->create([
            'managed_environment_id' => $tenant->getKey(),
            'user_id' => $user->getKey(),
            'role' => 'owner',
            'source' => 'manual',
            'source_ref' => null,
            'created_by_user_id' => null,
        ]);
    }

    $this
        ->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()])
        ->get('/admin/policies')
        ->assertNotFound();

    $this
        ->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()])
        ->get('/admin/policy-versions')
        ->assertNotFound();

    $this
        ->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()])
        ->get('/admin/backup-sets')
        ->assertNotFound();

    $this
        ->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()])
        ->get('/admin/inventory')
        ->assertNotFound();

    $this
        ->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()])
        ->get('/admin/inventory/inventory-coverage')
        ->assertNotFound();
});

it('allows tenant-scoped admin surfaces to load from the remembered canonical tenant', function (string $path): 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');

    $response = $this
        ->actingAs($user)
        ->withSession([
            WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id,
            WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY => [
                (string) $tenantA->workspace_id => (int) $tenantA->getKey(),
            ],
        ])
        ->get(match ($path) {
            '/admin/policies' => PolicyResource::getUrl(panel: 'admin', tenant: $tenantA),
            '/admin/policy-versions' => PolicyVersionResource::getUrl(panel: 'admin', tenant: $tenantA),
            '/admin/backup-sets' => BackupSetResource::getUrl(panel: 'admin', tenant: $tenantA),
            '/admin/inventory', '/admin/inventory/inventory-coverage' => InventoryCoverage::getUrl(panel: 'admin', tenant: $tenantA),
        });

    expect($response->getStatusCode())->toBeIn([200, 302]);
    expect($response->headers->get('Location'))->not->toBe('/admin/choose-environment');
})->with('admin tenant scoped surface paths');
