<?php

use App\Models\OperationRun;
use App\Services\OperationRunService;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;

it('detects a stale queued run that never started', function () {
    $run = OperationRun::factory()->create([
        'status' => OperationRunStatus::Queued->value,
        'started_at' => null,
        'created_at' => now()->subMinutes(6),
    ]);

    $service = app(OperationRunService::class);

    expect($service->isStaleQueuedRun($run))->toBeTrue();
});

it('does not treat recent queued runs as stale', function () {
    $run = OperationRun::factory()->create([
        'status' => OperationRunStatus::Queued->value,
        'started_at' => null,
        'created_at' => now()->subMinute(),
    ]);

    $service = app(OperationRunService::class);

    expect($service->isStaleQueuedRun($run))->toBeFalse();
});

it('fails a stale queued run and marks it completed', function () {
    $run = OperationRun::factory()->create([
        'status' => OperationRunStatus::Queued->value,
        'outcome' => OperationRunOutcome::Pending->value,
        'started_at' => null,
        'completed_at' => null,
        'failure_summary' => [],
    ]);

    $service = app(OperationRunService::class);

    $updated = $service->failStaleQueuedRun($run, message: 'Stale test run');

    expect($updated->status)->toBe(OperationRunStatus::Completed->value);
    expect($updated->outcome)->toBe(OperationRunOutcome::Failed->value);
    expect($updated->completed_at)->not->toBeNull();

    $failures = is_array($updated->failure_summary ?? null) ? $updated->failure_summary : [];

    expect($failures)->not->toBeEmpty();
    expect($failures[0]['code'] ?? null)->toBe('run.stale_queued');
});
