<?php

declare(strict_types=1);

use App\Filament\Resources\ManagedEnvironmentResource\Pages\ViewManagedEnvironment;
use App\Models\AuditLog;
use App\Models\ManagedEnvironment;
use App\Support\Audit\AuditActionId;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use Livewire\Livewire;

it('records archive and restore audit entries for tenant lifecycle mutations from the tenant view', function (): void {
    $tenant = ManagedEnvironment::factory()->active()->create(['name' => 'Lifecycle Audit ManagedEnvironment']);
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

    $this->actingAs($user);

    Filament::setTenant($tenant, true);

    Livewire::test(ViewManagedEnvironment::class, ['record' => $tenant->getRouteKey()])
        ->assertActionExists('archive', function (Action $action): bool {
            return $action->getLabel() === 'Archive' && $action->isConfirmationRequired();
        })
        ->mountAction('archive')
        ->setActionData([
            'archive_reason' => 'Retiring this tenant from active management.',
        ])
        ->callMountedAction()
        ->assertHasNoActionErrors();

    $tenant->refresh();

    expect($tenant->trashed())->toBeTrue();
    expect(AuditLog::query()
        ->where('workspace_id', (int) $tenant->workspace_id)
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('action', AuditActionId::TenantArchived->value)
        ->exists())->toBeTrue();

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

    expect(data_get($archiveAudit?->metadata, 'reason'))->toBe('Retiring this tenant from active management.');

    Filament::setTenant(null, true);

    Livewire::actingAs($user)
        ->test(ViewManagedEnvironment::class, ['record' => $tenant->getRouteKey()])
        ->assertActionExists('restore', function (Action $action): bool {
            return $action->getLabel() === 'Restore' && $action->isConfirmationRequired();
        })
        ->mountAction('restore')
        ->callMountedAction()
        ->assertHasNoActionErrors();

    $tenant->refresh();

    expect($tenant->trashed())->toBeFalse();
    expect(AuditLog::query()
        ->where('workspace_id', (int) $tenant->workspace_id)
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('action', AuditActionId::TenantRestored->value)
        ->exists())->toBeTrue();
});
