<?php

declare(strict_types=1);

use App\Models\EnhanceJob;
use App\Models\User;
use Illuminate\Support\Facades\Artisan;

it('renders text health output for enhance', function (): void {
    $owner = User::factory()->create();

    EnhanceJob::query()->create([
        'user_id' => $owner->id,
        'status' => EnhanceJob::STATUS_COMPLETED,
        'engine' => EnhanceJob::ENGINE_STUB,
        'mode' => 'standard',
        'scale' => 2,
        'processing_seconds' => 4,
        'finished_at' => now(),
    ]);

    $this->artisan('enhance:health')
        ->expectsOutputToContain('Enhance health')
        ->expectsOutputToContain('Configured engine')
        ->assertSuccessful();
});

it('renders json health output with stuck job counts', function (): void {
    config()->set('enhance.health.stuck_queued_after_minutes', 60);
    config()->set('enhance.health.stuck_processing_after_minutes', 30);
    config()->set('enhance.external_worker.url', null);

    $owner = User::factory()->create();

    EnhanceJob::query()->create([
        'user_id' => $owner->id,
        'status' => EnhanceJob::STATUS_QUEUED,
        'engine' => EnhanceJob::ENGINE_STUB,
        'mode' => 'standard',
        'scale' => 2,
        'queued_at' => now()->subMinutes(61),
    ]);

    EnhanceJob::query()->create([
        'user_id' => $owner->id,
        'status' => EnhanceJob::STATUS_PROCESSING,
        'engine' => EnhanceJob::ENGINE_STUB,
        'mode' => 'standard',
        'scale' => 2,
        'started_at' => now()->subMinutes(31),
    ]);

    EnhanceJob::query()->create([
        'user_id' => $owner->id,
        'status' => EnhanceJob::STATUS_COMPLETED,
        'engine' => EnhanceJob::ENGINE_STUB,
        'mode' => 'standard',
        'scale' => 2,
        'processing_seconds' => 8,
        'finished_at' => now(),
    ]);

    Artisan::call('enhance:health', ['--json' => true]);
    $payload = json_decode(Artisan::output(), true, 512, JSON_THROW_ON_ERROR);

    expect($payload['engine'])->toBe('stub');
    expect($payload['queue'])->toBe((string) config('enhance.queue', 'default'));
    expect($payload['worker_configured'])->toBeFalse();
    expect($payload['health']['stuck_queued'])->toBe(1);
    expect($payload['health']['stuck_processing'])->toBe(1);
    expect($payload['counts']['completed'])->toBe(1);
    expect($payload['today']['average_processing_seconds'])->toBe(8);
});