<?php

declare(strict_types=1);

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

it('sanitizes and truncates failure message suffix in terminal notifications', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);

    Filament::setTenant($tenant, true);

    $longMessage = "This is a very long failure message that should not be allowed to flood the notification UI.\n\n".
        str_repeat('x', 400);

    $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);

    $service->updateRun(
        $run,
        status: 'completed',
        outcome: 'failed',
        summaryCounts: ['total' => 1],
        failures: [[
            'code' => 'example.failure',
            'message' => $longMessage,
        ]],
    );

    $notification = $user->notifications()->latest('id')->first();
    expect($notification)->not->toBeNull();

    $body = (string) ($notification->data['body'] ?? '');

    expect($body)->toContain('Execution failed.');
    expect($body)->toContain('This is a very long failure message');
    expect($body)->toContain('Review the operation details before retrying.');

    // Ensure message is not full-length / multiline.
    expect($body)->not->toContain(str_repeat('x', 200));
    expect($body)->not->toContain("\n\nThis is a very long failure message");
})->group('ops-ux');
