<?php

declare(strict_types=1);

use App\Filament\Resources\ProviderConnectionResource;
use App\Models\ManagedEnvironment;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;

uses(RefreshDatabase::class);

test('ProviderConnectionResource::getUrl infers tenant from canonical referer query during Livewire requests', function (): void {
    $tenant = ManagedEnvironment::factory()->create([
        'external_id' => 'b0091e5d-944f-4a34-bcd9-12cbfb7b75cf',
    ]);
    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);

    $updateUri = '/'.collect(app('router')->getRoutes()->getRoutes())
        ->first(fn ($route): bool => str_contains((string) $route->getName(), 'livewire.update'))
        ?->uri();

    expect($updateUri)->toBeString();

    $request = Request::create($updateUri, 'POST');
    $request->headers->set('x-livewire', '1');
    $request->headers->set('referer', "http://localhost/admin/provider-connections/1/edit?environment_id={$tenant->getKey()}");
    app()->instance('request', $request);

    expect(ManagedEnvironment::query()->where('slug', $tenant->external_id)->exists())->toBeTrue();

    $method = new ReflectionMethod(ProviderConnectionResource::class, 'resolveScopedTenant');
    $method->setAccessible(true);
    $resolvedTenant = $method->invoke(null);

    expect($resolvedTenant)->toBeInstanceOf(ManagedEnvironment::class);
    expect($resolvedTenant->is($tenant))->toBeTrue();

    $url = ProviderConnectionResource::getUrl('create');

    expect($url)->toContain('/admin/provider-connections');
    expect($url)->toContain('environment_id='.(string) $tenant->getKey());
});
