<?php

use App\Filament\Resources\TenantResource\Pages\ListTenants;
use App\Models\Tenant;
use App\Models\User;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

test('make current action marks exactly one tenant as current', function () {
    $originalEnv = getenv('INTUNE_TENANT_ID');
    putenv('INTUNE_TENANT_ID=');

    $first = Tenant::create([
        'tenant_id' => 'tenant-one',
        'name' => 'Tenant One',
        'is_current' => true,
    ]);

    $second = Tenant::create([
        'tenant_id' => 'tenant-two',
        'name' => 'Tenant Two',
        'is_current' => false,
    ]);

    $user = User::factory()->create();
    $this->actingAs($user);
    $user->tenants()->syncWithoutDetaching([
        $first->getKey() => ['role' => 'owner'],
        $second->getKey() => ['role' => 'owner'],
    ]);
    Filament::setTenant($first, true);

    Livewire::test(ListTenants::class)
        ->callTableAction('makeCurrent', $second);

    expect(Tenant::find($second->id)->is_current)->toBeTrue();
    expect(Tenant::find($first->id)->is_current)->toBeFalse();
    expect(Tenant::query()->where('is_current', true)->count())->toBe(1);

    $originalEnv !== false
        ? putenv("INTUNE_TENANT_ID={$originalEnv}")
        : putenv('INTUNE_TENANT_ID');
});
