<?php

use App\Support\SourceErrorPresenter;

test('returns null for an empty error', function () {
    expect(SourceErrorPresenter::present(null))->toBeNull();
    expect(SourceErrorPresenter::present(''))->toBeNull();
    expect(SourceErrorPresenter::present('   '))->toBeNull();
});

test('hides Cloudflare Browser Rendering 401 with a customer-safe line', function () {
    $raw = 'Crawl failed: Cloudflare Browser Rendering HTTP 401: {"result":null,"success":false,"errors":[{"code":10000,"message":"Authentication error"}],"messages":[]}';

    $msg = SourceErrorPresenter::present($raw);

    expect($msg)->not->toContain('Cloudflare');
    expect($msg)->not->toContain('401');
    expect($msg)->not->toContain('Authentication');
    expect($msg)->toContain('crawl service is temporarily unavailable');
});

test('hides Cloudflare 429 rate-limit body', function () {
    $raw = 'Crawl failed: Cloudflare Browser Rendering rate-limited (429).';

    $msg = SourceErrorPresenter::present($raw);

    expect($msg)->not->toContain('Cloudflare');
    expect($msg)->not->toContain('429');
    expect($msg)->toContain('busy right now');
});

test('hides 404 from the target site with a friendly line', function () {
    $raw = 'Crawl failed: HTTP 404 — page not found at https://example.com/missing';

    $msg = SourceErrorPresenter::present($raw);

    expect($msg)->not->toContain('https://example.com');
    expect($msg)->toContain('404');
    expect($msg)->toContain("couldn't find this page");
});

test('hides cURL timeout body', function () {
    $raw = 'Crawl failed: cURL error 28: Operation timed out after 30001 milliseconds';

    $msg = SourceErrorPresenter::present($raw);

    expect($msg)->not->toContain('cURL');
    expect($msg)->not->toContain('28');
    expect($msg)->toContain("couldn't reach this page");
});

test('returns a generic fallback for an unrecognised internal error', function () {
    $raw = 'Crawl failed: Something obscure happened deep in the parser';

    $msg = SourceErrorPresenter::present($raw);

    expect($msg)->toBe("Couldn't index this page.");
    expect($msg)->not->toContain('parser');
});

test('SSRF guard surfaces a safety-oriented message', function () {
    $raw = 'Crawl failed: Forbidden host 169.254.169.254 (cloud metadata endpoint)';

    $msg = SourceErrorPresenter::present($raw);

    expect($msg)->not->toContain('169.254');
    expect($msg)->toContain('safety reasons');
});
