<?php

declare(strict_types=1);

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('excludes closed workspaces from the workspace chooser', function (): void {
    $user = User::factory()->create();
    $openWorkspace = Workspace::factory()->create(['name' => 'Open Workspace']);
    $closedWorkspace = Workspace::factory()->create([
        'name' => 'Closed Workspace',
        'closed_at' => now(),
        'closed_reason' => 'No longer active.',
    ]);

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

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

    $this->actingAs($user)
        ->get(route('filament.admin.pages.choose-workspace'))
        ->assertSuccessful()
        ->assertSee('Open Workspace')
        ->assertDontSee('Closed Workspace');
});

it('clears closed remembered workspace context and routes to explicit recovery', function (): void {
    $user = User::factory()->create();
    $openWorkspace = Workspace::factory()->create();
    $closedWorkspace = Workspace::factory()->create([
        'closed_at' => now(),
        'closed_reason' => 'The workspace was closed by support.',
    ]);

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

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

    $user->forceFill(['last_workspace_id' => (int) $closedWorkspace->getKey()])->save();

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $closedWorkspace->getKey()])
        ->get('/admin/_test/workspace-context')
        ->assertRedirect('/admin/choose-workspace')
        ->assertSessionMissing(WorkspaceContext::SESSION_KEY);

    expect($user->fresh()->last_workspace_id)->toBeNull();
});
