<?php

app_require('modules/economic/economic_m.php');
app_require('modules/economic/customers/economicCustomers.php');

use customers\economicCustomers;

if (!class_exists('EconomicCustomersListResponseProbe')) {
    class EconomicCustomersListResponseProbe extends economicCustomers
    {
        private string $stubResponse = '{}';

        public function __construct()
        {
            // No-op: tests stub network responses directly.
        }

        public function setStubResponse(string $response): void
        {
            $this->stubResponse = $response;
        }

        protected function send_request($url, $method, $data = '', bool $authToken2 = false): string
        {
            return $this->stubResponse;
        }
    }
}

it('accepts valid list payloads that include collection and pagination results', function (): void {
    $probe = new EconomicCustomersListResponseProbe();
    $probe->setStubResponse(json_encode([
        'collection' => [
            ['customerNumber' => 1000, 'name' => 'Acme A/S'],
        ],
        'pagination' => [
            'results' => 1,
        ],
    ]));

    $result = $probe->listCustomers(1, 100, 'acme', null);

    expect($result)->toBeObject();
    expect(isset($result->collection))->toBeTrue();
    expect(is_array($result->collection))->toBeTrue();
    expect($result->collection[0]->customerNumber)->toBe(1000);
    expect($result->pagination->results)->toBe(1);
});

it('throws when pagination is missing from the response payload', function (): void {
    $probe = new EconomicCustomersListResponseProbe();
    $probe->setStubResponse(json_encode([
        'collection' => [
            ['customerNumber' => 1000, 'name' => 'Acme A/S'],
        ],
    ]));

    expect(fn() => $probe->listCustomers(1, 100, null, null))
        ->toThrow(RuntimeException::class, 'missing pagination');
});

it('throws when upstream responds with an error-shaped payload', function (): void {
    $probe = new EconomicCustomersListResponseProbe();
    $probe->setStubResponse(json_encode([
        'message' => 'Could not parse query string filter.',
        'errors' => ['Filtering is not allowed on property \'invalidField\'.'],
        'httpStatusCode' => 400,
    ]));

    expect(fn() => $probe->listCustomers(1, 100, 'foo', null))
        ->toThrow(RuntimeException::class, 'Could not parse query string filter.');
});
