<?php

declare(strict_types=1);

use App\Filament\Resources\ProviderConnectionResource\Pages\EditProviderConnection;
use App\Models\ManagedEnvironment;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('EditProviderConnection prefers scoped tenant external id over ManagedEnvironment::current', function (): void {
    $tenantA = ManagedEnvironment::factory()->create();
    $tenantB = ManagedEnvironment::factory()->create();

    $tenantB->makeCurrent();

    $page = app(EditProviderConnection::class);
    $page->scopedTenantExternalId = (string) $tenantA->external_id;

    $method = new ReflectionMethod($page, 'currentTenant');
    $method->setAccessible(true);

    $resolvedTenant = $method->invoke($page);

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

test('EditProviderConnection falls back to ManagedEnvironment::current when no scoped tenant is set', function (): void {
    $tenantA = ManagedEnvironment::factory()->create();

    $tenantA->makeCurrent();

    $page = app(EditProviderConnection::class);

    $method = new ReflectionMethod($page, 'currentTenant');
    $method->setAccessible(true);

    $resolvedTenant = $method->invoke($page);

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