<?php

it('maps e-conomic integration failures in customer listing to explicit 502 responses', function (): void {
    $routeFile = app_path('routes/customerSearchRoute.php');
    $content = file_get_contents($routeFile);

    expect($content)->not->toBeFalse();
    expect($content)->toContain("catch (\\Throwable \$throwable)");
    expect($content)->toContain("'LIST_CUSTOMERS_FAILED'");
    expect($content)->toContain("'message' => 'Failed to fetch customers from e-conomic'");
    expect($content)->toContain("'upstream_message' => \$upstreamMessage");
    expect($content)->toContain("], 502);");
});

it('logs LIST_CUSTOMERS success only after pagination and customer mapping are completed', function (): void {
    $routeFile = app_path('routes/customerSearchRoute.php');
    $content = file_get_contents($routeFile);

    expect($content)->not->toBeFalse();

    $paginatePosition = strpos($content, '$response->paginate(');
    $successLogPosition = strpos($content, "'LIST_CUSTOMERS', 'Successfully listed customers'");

    expect($paginatePosition)->not->toBeFalse();
    expect($successLogPosition)->not->toBeFalse();
    expect($successLogPosition)->toBeGreaterThan($paginatePosition);
});

it('guards against malformed customer list payloads before calling paginate', function (): void {
    $routeFile = app_path('routes/customerSearchRoute.php');
    $content = file_get_contents($routeFile);

    expect($content)->not->toBeFalse();
    expect($content)->toContain('missing pagination results');
    expect($content)->toContain('missing customer collection');
});
