<?php

declare(strict_types=1);

use App\Jobs\ProviderConnectionHealthCheckJob;
use App\Models\OperationRun;
use App\Models\ProviderConnection;
use App\Models\ProviderCredential;
use App\Services\OperationRunService;
use App\Services\Verification\StartVerification;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Queue;

it('creates a new verification run after the previous run is completed', function (): void {
    Queue::fake();

    [$user, $tenant] = createUserWithTenant(role: 'operator');
    $this->actingAs($user);

    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    $connection = ProviderConnection::factory()->create([
        'tenant_id' => $tenant->getKey(),
        'provider' => 'microsoft',
        'entra_tenant_id' => fake()->uuid(),
        'status' => 'connected',
    ]);
    ProviderCredential::factory()->create([
        'provider_connection_id' => (int) $connection->getKey(),
    ]);

    $starter = app(StartVerification::class);

    $first = $starter->providerConnectionCheck(
        tenant: $tenant,
        connection: $connection,
        initiator: $user,
    );

    /** @var OperationRun $firstRun */
    $firstRun = $first->run->refresh();

    app(OperationRunService::class)->updateRun(
        $firstRun,
        status: OperationRunStatus::Completed->value,
        outcome: OperationRunOutcome::Succeeded->value,
    );

    $second = $starter->providerConnectionCheck(
        tenant: $tenant,
        connection: $connection,
        initiator: $user,
    );

    expect($second->status)->toBe('started');
    expect($second->run->getKey())->not->toBe($firstRun->getKey());

    expect(OperationRun::query()
        ->where('tenant_id', $tenant->getKey())
        ->where('type', 'provider.connection.check')
        ->count())->toBe(2);

    Queue::assertPushed(ProviderConnectionHealthCheckJob::class, 2);
});
