<?php

use App\Livewire\Admin\Provisioning;
use App\Models\Host;
use App\Models\ProvisioningRun;
use App\Provisioning\Jobs\AdvanceRunJob;
use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;

// admin() helper defined in HostManagementTest.

it('retries a failed run from the provisioning console', function () {
    Queue::fake();
    $host = Host::factory()->create(['status' => 'error']);
    $run = ProvisioningRun::factory()->create([
        'subject_type' => Host::class, 'subject_id' => $host->id, 'pipeline' => 'host',
        'status' => ProvisioningRun::STATUS_FAILED, 'attempt' => 3, 'current_step' => 4, 'error' => 'boom',
    ]);

    Livewire::actingAs(admin(), 'operator')->test(Provisioning::class)->call('retry', $run->uuid);

    $run->refresh();
    expect($run->status)->toBe(ProvisioningRun::STATUS_RUNNING)
        ->and($run->attempt)->toBe(0)
        ->and($run->error)->toBeNull()
        ->and($host->fresh()->status)->toBe('onboarding');
    Queue::assertPushed(AdvanceRunJob::class);
});

it('ignores retry on a run that is not failed', function () {
    Queue::fake();
    $host = Host::factory()->active()->create();
    $run = ProvisioningRun::factory()->create([
        'subject_type' => Host::class, 'subject_id' => $host->id, 'pipeline' => 'host',
        'status' => ProvisioningRun::STATUS_RUNNING,
    ]);

    Livewire::actingAs(admin(), 'operator')->test(Provisioning::class)->call('retry', $run->uuid);

    expect($run->fresh()->status)->toBe(ProvisioningRun::STATUS_RUNNING);
    Queue::assertNotPushed(AdvanceRunJob::class);
});
