<?php

declare(strict_types=1);

use App\Models\ManagedEnvironment;
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('shows the managed-tenants CTA when a workspace has no selectable active tenants', function (): void {
    $user = User::factory()->create();
    $workspace = Workspace::factory()->create();

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

    $onboardingTenant = ManagedEnvironment::factory()->onboarding()->create([
        'workspace_id' => (int) $workspace->getKey(),
    ]);

    $user->tenants()->syncWithoutDetaching([
        $onboardingTenant->getKey() => ['role' => 'owner'],
    ]);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()])
        ->get('/admin/choose-environment')
        ->assertSuccessful()
        ->assertSee(__('localization.shell.no_active_environments'))
        ->assertSee(__('localization.shell.view_managed_environments'))
        ->assertDontSee('Register tenant')
        ->assertDontSee('Add tenant');
});

it('keeps the empty state safe for readonly workspace members', function (): void {
    $user = User::factory()->create();
    $workspace = Workspace::factory()->create();

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

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()])
        ->get('/admin/choose-environment')
        ->assertSuccessful()
        ->assertSee(__('localization.shell.no_active_environments'))
        ->assertSee('Switch workspace')
        ->assertDontSee('Register tenant');
});
