<?php

declare(strict_types=1);

use App\Jobs\ProviderConnectionHealthCheckJob;
use App\Models\OperationRun;
use App\Models\ProviderConnection;
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', fixtureProfile: 'credential-enabled');
    $this->actingAs($user);

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

    $connection = ProviderConnection::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('provider', 'microsoft')
        ->where('is_default', true)
        ->firstOrFail();

    $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('managed_environment_id', $tenant->getKey())
        ->where('type', 'provider.connection.check')
        ->count())->toBe(2);

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