<?php

declare(strict_types=1);

use App\Models\OperationRun;
use App\Services\OperationRunService;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('operation run service increments whitelisted summary counts', function (): void {
    $run = OperationRun::factory()->create([
        'status' => 'queued',
        'outcome' => 'pending',
        'summary_counts' => [
            'processed' => 0,
            'succeeded' => 0,
            'failed' => 0,
            'skipped' => 0,
        ],
    ]);

    /** @var OperationRunService $service */
    $service = app(OperationRunService::class);

    $service->incrementSummaryCounts($run, [
        'processed' => 3,
        'succeeded' => 1,
        'skipped' => 1,
        'failed' => 1,
        'secrets' => 999,
    ]);

    $run->refresh();

    expect($run->summary_counts)->toMatchArray([
        'processed' => 3,
        'succeeded' => 1,
        'skipped' => 1,
        'failed' => 1,
    ]);
    expect($run->summary_counts)->not->toHaveKey('secrets');
});

test('operation run service completes bulk runs based on summary counts', function (): void {
    /** @var OperationRunService $service */
    $service = app(OperationRunService::class);

    $succeeded = OperationRun::factory()->create([
        'status' => 'running',
        'outcome' => 'pending',
        'summary_counts' => [
            'total' => 3,
            'processed' => 3,
            'failed' => 0,
        ],
    ]);

    $service->maybeCompleteBulkRun($succeeded);
    $succeeded->refresh();
    expect($succeeded->status)->toBe('completed')
        ->and($succeeded->outcome)->toBe('succeeded');

    $partial = OperationRun::factory()->create([
        'status' => 'running',
        'outcome' => 'pending',
        'summary_counts' => [
            'total' => 3,
            'processed' => 3,
            'failed' => 1,
        ],
    ]);

    $service->maybeCompleteBulkRun($partial);
    $partial->refresh();
    expect($partial->status)->toBe('completed')
        ->and($partial->outcome)->toBe('partially_succeeded');

    $failed = OperationRun::factory()->create([
        'status' => 'running',
        'outcome' => 'pending',
        'summary_counts' => [
            'total' => 3,
            'processed' => 3,
            'failed' => 3,
        ],
    ]);

    $service->maybeCompleteBulkRun($failed);
    $failed->refresh();
    expect($failed->status)->toBe('completed')
        ->and($failed->outcome)->toBe('failed');
});
