<?php

declare(strict_types=1);

use App\Filament\Pages\Workspaces\ManagedTenantOnboardingWizard;
use App\Models\AuditLog;
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;

it('denies activation to non-owners even when verification succeeded', function (): void {
    Queue::fake();

    $workspace = Workspace::factory()->create();
    $user = User::factory()->create();

    WorkspaceMembership::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'user_id' => (int) $user->getKey(),
        'role' => 'manager',
    ]);

    session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());

    $entraTenantId = '88888888-8888-8888-8888-888888888888';

    $component = Livewire::actingAs($user)->test(ManagedTenantOnboardingWizard::class);

    $component->call('identifyManagedTenant', [
        'entra_tenant_id' => $entraTenantId,
        'environment' => 'prod',
        'name' => 'Acme',
    ]);

    $component->call('createProviderConnection', [
        'display_name' => 'Acme connection',
        'client_id' => '00000000-0000-0000-0000-000000000000',
        'client_secret' => 'super-secret',
        'is_default' => true,
    ]);

    $component->call('startVerification');

    $tenant = Tenant::query()->where('tenant_id', $entraTenantId)->firstOrFail();

    $run = OperationRun::query()
        ->where('tenant_id', (int) $tenant->getKey())
        ->where('type', 'provider.connection.check')
        ->firstOrFail();

    $run->update([
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Succeeded->value,
    ]);

    $component
        ->call('completeOnboarding')
        ->assertStatus(403);

    $tenant->refresh();
    expect($tenant->status)->not->toBe(Tenant::STATUS_ACTIVE);
});

it('requires an override reason when verification is blocked and records an audit event when overridden', function (): void {
    Queue::fake();

    $workspace = Workspace::factory()->create();
    $user = User::factory()->create();

    WorkspaceMembership::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'user_id' => (int) $user->getKey(),
        'role' => 'owner',
    ]);

    session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());

    $entraTenantId = '99999999-9999-9999-9999-999999999999';

    $component = Livewire::actingAs($user)->test(ManagedTenantOnboardingWizard::class);

    $component->call('identifyManagedTenant', [
        'entra_tenant_id' => $entraTenantId,
        'environment' => 'prod',
        'name' => 'Acme',
    ]);

    $component->call('createProviderConnection', [
        'display_name' => 'Acme connection',
        'client_id' => '00000000-0000-0000-0000-000000000000',
        'client_secret' => 'super-secret',
        'is_default' => true,
    ]);

    $component->call('startVerification');

    $tenant = Tenant::query()->where('tenant_id', $entraTenantId)->firstOrFail();

    $run = OperationRun::query()
        ->where('tenant_id', (int) $tenant->getKey())
        ->where('type', 'provider.connection.check')
        ->firstOrFail();

    $run->update([
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Failed->value,
    ]);

    $component
        ->set('data.override_blocked', true)
        ->set('data.override_reason', '')
        ->call('completeOnboarding')
        ->assertHasErrors(['data.override_reason']);

    $component
        ->set('data.override_blocked', true)
        ->set('data.override_reason', 'Temporary exception approved by owner')
        ->call('completeOnboarding');

    $tenant->refresh();
    expect($tenant->status)->toBe(Tenant::STATUS_ACTIVE);

    expect(AuditLog::query()
        ->where('workspace_id', (int) $workspace->getKey())
        ->where('action', 'managed_tenant_onboarding.activation')
        ->exists())->toBeTrue();
});
