<?php

declare(strict_types=1);

use App\Support\ManagedEnvironmentLinks;
use App\Support\Workspaces\WorkspaceContext;
use App\Support\Workspaces\WorkspaceIntendedUrl;
use App\Support\Workspaces\WorkspaceRedirectResolver;

it('does not store retired tenant route intended URLs', function (string $path): void {
    WorkspaceIntendedUrl::store($path);

    expect(session()->get(WorkspaceContext::INTENDED_URL_SESSION_KEY))->toBeNull();
})->with([
    '/admin/t',
    '/admin/t/example',
    '/admin/tenants',
    '/admin/tenants/example',
    '/admin/tenants/example/required-permissions',
    '/admin/tenants/example/provider-connections',
]);

it('drops unsafe external intended URLs on consume', function (): void {
    session()->put(WorkspaceContext::INTENDED_URL_SESSION_KEY, 'https://example.test/admin/workspaces/1/environments');

    expect(WorkspaceIntendedUrl::consume())->toBeNull();
});

it('rejects retired intended URLs and falls back to the canonical environment destination', function (string $intendedUrl): void {
    [$user, $tenant] = createMinimalUserWithTenant(role: 'owner');
    $workspace = $tenant->workspace()->firstOrFail();

    $resolved = app(WorkspaceRedirectResolver::class)->resolve($workspace, $user, $intendedUrl);

    expect($resolved)->toBe(ManagedEnvironmentLinks::viewUrl($tenant))
        ->and($resolved)->not->toContain('/admin/tenants')
        ->and($resolved)->not->toContain('/admin/t/');
})->with([
    '/admin/t/example',
    '/admin/tenants',
    '/admin/tenants/example',
    '/admin/tenants/example/provider-connections',
    'https://example.test/admin/tenants/example',
]);

it('normalizes legacy operations intended URL to the workspace-scoped operations route', function (): void {
    [$user, $tenant] = createMinimalUserWithTenant(role: 'owner');
    $workspace = $tenant->workspace()->firstOrFail();

    $resolved = app(WorkspaceRedirectResolver::class)->resolve($workspace, $user, '/admin/operations?activeTab=active');

    expect($resolved)->toBe(ManagedEnvironmentLinks::operationsUrl($workspace, ['activeTab' => 'active']))
        ->and($resolved)->toContain('/admin/workspaces/')
        ->and($resolved)->not->toContain('/admin/operations?');
});

it('does not preserve ambiguous legacy operation detail intended URLs', function (): void {
    [$user, $tenant] = createMinimalUserWithTenant(role: 'owner');
    $workspace = $tenant->workspace()->firstOrFail();

    $resolved = app(WorkspaceRedirectResolver::class)->resolve($workspace, $user, '/admin/operations/123');

    expect($resolved)->toBe(ManagedEnvironmentLinks::viewUrl($tenant));
});

