<?php

declare(strict_types=1);

use App\Jobs\ComposeEnvironmentReviewJob;
use App\Jobs\Concerns\BridgesFailedOperationRun;
use App\Models\OperationRun;
use App\Notifications\OperationRunCompleted;
use App\Support\OperationCatalog;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OperationRunType;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Queue;

it('queues review composition on the canonical operation-run type and sends the terminal notification after completion', function (): void {
    Queue::fake();
    Notification::fake();

    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $snapshot = seedEnvironmentReviewEvidence($tenant, operationRunCount: 3);

    $review = app(\App\Services\EnvironmentReviews\EnvironmentReviewService::class)->create($tenant, $snapshot, $user);
    $run = OperationRun::query()->findOrFail($review->operation_run_id);

    expect($run->type)->toBe(OperationRunType::EnvironmentReviewCompose->value)
        ->and(OperationCatalog::label((string) $run->type))->toBe('Review composition')
        ->and(data_get($run->context, 'progress.composite.operation_count'))->toBe(3)
        ->and(data_get($run->context, 'progress.composite.label'))->toBe('Review composition is aggregating 3 operations.');

    Queue::assertPushed(ComposeEnvironmentReviewJob::class);

    $job = new ComposeEnvironmentReviewJob((int) $review->getKey(), (int) $run->getKey());
    app()->call([$job, 'handle']);

    $run->refresh();

    expect($run->status)->toBe(OperationRunStatus::Completed->value)
        ->and($run->outcome)->toBe(OperationRunOutcome::Succeeded->value);

    Notification::assertSentTo($user, OperationRunCompleted::class);
});

it('declares the environment review lifecycle contract explicitly', function (): void {
    $job = new ComposeEnvironmentReviewJob(environmentReviewId: 1, operationRunId: 1);

    expect(class_uses_recursive($job))->toContain(BridgesFailedOperationRun::class)
        ->and($job->timeout)->toBe(240)
        ->and($job->failOnTimeout)->toBeTrue();
});
