<?php

declare(strict_types=1);

use App\Filament\Resources\BaselineProfileResource\Pages\EditBaselineProfile;
use App\Filament\Resources\BaselineProfileResource\RelationManagers\BaselineTenantAssignmentsRelationManager;
use App\Models\BaselineProfile;
use App\Models\BaselineTenantAssignment;
use App\Models\ManagedEnvironment;
use Filament\Forms\Components\Select;
use Livewire\Livewire;

it('shows already assigned tenants as disabled with their baseline label', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $currentProfile = BaselineProfile::factory()->active()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'name' => 'Current Baseline',
    ]);

    $otherProfile = BaselineProfile::factory()->active()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'name' => 'Device Hardening',
    ]);

    BaselineTenantAssignment::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'baseline_profile_id' => (int) $currentProfile->getKey(),
    ]);

    $assignedTenant = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'name' => 'Already Assigned ManagedEnvironment',
    ]);

    $availableTenant = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'name' => 'Available ManagedEnvironment',
    ]);

    BaselineTenantAssignment::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $assignedTenant->getKey(),
        'baseline_profile_id' => (int) $otherProfile->getKey(),
    ]);

    Livewire::actingAs($user)
        ->test(BaselineTenantAssignmentsRelationManager::class, [
            'ownerRecord' => $currentProfile,
            'pageClass' => EditBaselineProfile::class,
        ])
        ->mountTableAction('assign')
        ->assertFormFieldExists('managed_environment_id', function (Select $field) use ($assignedTenant, $availableTenant, $otherProfile): bool {
            $options = $field->getOptions();

            $assignedTenantKey = (int) $assignedTenant->getKey();
            $availableTenantKey = (int) $availableTenant->getKey();

            $assignedLabel = $options[$assignedTenantKey] ?? $options[(string) $assignedTenantKey] ?? null;
            $availableLabel = $options[$availableTenantKey] ?? $options[(string) $availableTenantKey] ?? null;

            return $field->isSearchable()
                && $assignedLabel === 'Already Assigned ManagedEnvironment (assigned to baseline: '.$otherProfile->name.')'
                && $field->isOptionDisabled($assignedTenantKey, $assignedLabel)
                && $availableLabel === 'Available ManagedEnvironment'
                && ! $field->isOptionDisabled($availableTenantKey, $availableLabel);
        });
});
