<?php

declare(strict_types=1);

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);

it('only shows tenants from the currently selected workspace on choose-environment', function (): void {
    $user = User::factory()->create();

    $workspaceA = Workspace::factory()->create(['name' => 'Workspace A']);
    $workspaceB = Workspace::factory()->create(['name' => 'Workspace B']);

    $tenantA = ManagedEnvironment::factory()->create([
        'workspace_id' => $workspaceA->getKey(),
        'name' => 'ManagedEnvironment A',
        'status' => 'active',
    ]);

    $tenantB = ManagedEnvironment::factory()->create([
        'workspace_id' => $workspaceB->getKey(),
        'name' => 'ManagedEnvironment B',
        'status' => 'active',
    ]);

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

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

    ManagedEnvironmentMembership::query()->create([
        'managed_environment_id' => $tenantA->getKey(),
        'user_id' => $user->getKey(),
        'role' => 'owner',
        'source' => 'manual',
        'source_ref' => null,
        'created_by_user_id' => null,
    ]);

    ManagedEnvironmentMembership::query()->create([
        'managed_environment_id' => $tenantB->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) $workspaceA->getKey()])
        ->get('/admin/choose-environment')
        ->assertSuccessful()
        ->assertSee('ManagedEnvironment A')
        ->assertDontSee('ManagedEnvironment B');
});
