<?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('redirects to managed tenants after switching to a workspace with no tenants', function (): void {
    $user = User::factory()->create();

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

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

    $response = $this
        ->actingAs($user)
        ->post(route('admin.switch-workspace'), ['workspace_id' => (int) $workspace->getKey()]);

    $response->assertRedirect();

    $location = $response->headers->get('Location');
    expect($location)->toBe(url('/admin/workspaces/'.$workspace->slug.'/environments'));

    expect(session(WorkspaceContext::SESSION_KEY))->toBe((int) $workspace->getKey());
});
