<?php

declare(strict_types=1);

use App\Models\OperationRun;
use App\Services\OperationRunService;
use Filament\Facades\Filament;

it('emits a terminal database notification only once per run', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);

    Filament::setTenant($tenant, true);

    $run = OperationRun::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'user_id' => $user->getKey(),
        'initiator_name' => $user->name,
        'type' => 'inventory_sync',
        'status' => 'running',
        'outcome' => 'pending',
        'context' => ['scope' => 'all'],
    ]);

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

    expect($user->notifications()->count())->toBe(0);

    $service->updateRun(
        $run,
        status: 'completed',
        outcome: 'succeeded',
        summaryCounts: ['total' => 1],
        failures: [],
    );

    expect($user->notifications()->count())->toBe(1);

    // Even if some downstream code re-applies a terminal update, we never spam.
    $service->updateRun(
        $run,
        status: 'completed',
        outcome: 'failed',
        summaryCounts: ['total' => 2],
        failures: [['code' => 'repeat.terminal', 'message' => 'should not notify again']],
    );

    expect($user->notifications()->count())->toBe(1);
})->group('ops-ux');
