<?php

declare(strict_types=1);

use App\Filament\Resources\ManagedEnvironmentResource\Pages\ViewManagedEnvironment;
use App\Models\AuditLog;
use App\Models\ManagedEnvironment;
use App\Models\OperationRun;
use App\Services\Entitlements\WorkspaceCommercialLifecycleResolver;
use App\Services\OperationRunService;
use App\Services\ReviewPackService;
use App\Support\Audit\AuditActionId;
use App\Support\OperationRunType;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Livewire\Livewire;

uses(RefreshDatabase::class);

beforeEach(function (): void {
    Filament::setCurrentPanel('admin');
    Filament::bootCurrentPanel();
});

it('removes and restores a tenant from workspace context without deleting history', function (): void {
    $tenant = ManagedEnvironment::factory()->active()->create([
        'name' => 'Removal ManagedEnvironment',
        'is_current' => true,
    ]);
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

    $this->actingAs($user);
    Filament::setTenant($tenant, true);

    Livewire::test(ViewManagedEnvironment::class, ['record' => $tenant->getRouteKey()])
        ->assertActionVisible('remove_from_workspace')
        ->assertActionExists('remove_from_workspace', fn (Action $action): bool => $action->isConfirmationRequired())
        ->callAction('remove_from_workspace', data: [
            'removal_reason' => 'Tenant was removed from active workspace operations.',
        ])
        ->assertHasNoActionErrors()
        ->assertNotified('Tenant removed from workspace');

    $tenant->refresh();

    expect($tenant->isRemovedFromWorkspace())->toBeTrue()
        ->and($tenant->is_current)->toBeFalse()
        ->and($tenant->workspaceRemovalReason())->toBe('Tenant was removed from active workspace operations.')
        ->and($tenant->isSelectableAsContext())->toBeFalse()
        ->and(DB::table('managed_environment_memberships')
            ->where('managed_environment_id', (int) $tenant->getKey())
            ->where('user_id', (int) $user->getKey())
            ->exists())->toBeTrue();

    $removeAudit = AuditLog::query()
        ->where('workspace_id', (int) $tenant->workspace_id)
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('action', AuditActionId::TenantRemovedFromWorkspace->value)
        ->latest('id')
        ->first();

    expect($removeAudit)->not->toBeNull()
        ->and($removeAudit?->metadata['reason'] ?? null)->toBe('Tenant was removed from active workspace operations.')
        ->and($removeAudit?->metadata['after_status'] ?? null)->toBe('removed_from_workspace');

    $decision = app(ReviewPackService::class)->reviewPackGenerationDecisionForTenant($tenant->fresh());

    expect($decision['is_blocked'])->toBeTrue()
        ->and($decision['reason_family'])->toBe(WorkspaceCommercialLifecycleResolver::REASON_FAMILY_TENANT_WORKSPACE_REMOVAL);

    expect(fn () => app(OperationRunService::class)->ensureRun(
        tenant: $tenant->fresh(),
        type: OperationRunType::InventorySync->value,
        inputs: ['scope' => 'tenant_removal_test'],
        initiator: $user,
    ))->toThrow(InvalidArgumentException::class, 'removed from the workspace');

    expect(OperationRun::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->exists())->toBeFalse();

    Livewire::actingAs($user)
        ->test(ViewManagedEnvironment::class, ['record' => $tenant->getRouteKey()])
        ->assertSee('Removed from workspace');

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get('/admin/t/'.$tenant->external_id)
        ->assertNotFound();

    Filament::setTenant(null, true);

    Livewire::actingAs($user)
        ->test(ViewManagedEnvironment::class, ['record' => $tenant->getRouteKey()])
        ->assertActionVisible('restore_to_workspace')
        ->assertActionExists('restore_to_workspace', fn (Action $action): bool => $action->isConfirmationRequired())
        ->callAction('restore_to_workspace', data: [
            'restore_reason' => 'Tenant is approved for active workspace operations again.',
        ])
        ->assertHasNoActionErrors()
        ->assertNotified('Tenant restored to workspace');

    $tenant->refresh();

    expect($tenant->isRemovedFromWorkspace())->toBeFalse()
        ->and($tenant->workspaceRemovalReason())->toBeNull()
        ->and($tenant->isSelectableAsContext())->toBeTrue()
        ->and(AuditLog::query()
            ->where('workspace_id', (int) $tenant->workspace_id)
            ->where('managed_environment_id', (int) $tenant->getKey())
            ->where('action', AuditActionId::TenantRestoredToWorkspace->value)
            ->where('metadata->reason', 'Tenant is approved for active workspace operations again.')
            ->exists())->toBeTrue();
});
