<?php

use App\Models\Tenant;
use App\Models\User;
use Filament\PanelRegistry;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('only returns membership tenants for normal users', function () {
    $user = User::factory()->create();

    $allowed = Tenant::factory()->create(['name' => 'Allowed']);
    $blocked = Tenant::factory()->create(['name' => 'Blocked']);

    $user->tenants()->syncWithoutDetaching([
        $allowed->getKey() => ['role' => 'readonly'],
    ]);

    /** @var \Filament\Panel $panel */
    $panel = app(PanelRegistry::class)->get('admin');

    $tenants = $user->getTenants($panel);

    expect($tenants)->toHaveCount(1);
    expect($tenants->first()?->getKey())->toBe($allowed->getKey());
    expect($tenants->first()?->name)->toBe('Allowed');

    expect($tenants->contains(fn (Tenant $tenant) => $tenant->getKey() === $blocked->getKey()))->toBeFalse();
});

it('returns all active tenants for platform superadmins', function () {
    $user = User::factory()->create();

    $a = Tenant::factory()->create(['name' => 'A']);
    $b = Tenant::factory()->create(['name' => 'B']);

    /** @var \Filament\Panel $panel */
    $panel = app(PanelRegistry::class)->get('admin');

    $tenants = $user->getTenants($panel);

    expect($tenants)->toHaveCount(0);
});
