<?php

declare(strict_types=1);

use App\Filament\Resources\ProviderConnectionResource;
use App\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;

uses(RefreshDatabase::class);

test('ProviderConnectionResource::getUrl infers tenant from referer during Livewire requests', function (): void {
    $tenant = Tenant::factory()->create([
        'external_id' => 'b0091e5d-944f-4a34-bcd9-12cbfb7b75cf',
    ]);

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

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

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

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

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

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