<?php

declare(strict_types=1);

/**
 * Test offline delle operazioni report (ListReports/GetReport).
 *
 * Nessuna rete e nessuna credenziale: il Guzzle iniettato serve token + risposte
 * API dalla coda del MockHandler. Il contratto (path /reports/v1, forma delle
 * risposte) deriva dall'implementazione in produzione nel progetto data-layer.
 */

$listReportsPayload = [
    'reports' => [
        [
            'filename' => 'blazemedia-tracking_id-report-20260730.tsv.gz',
            'md5' => 'd41d8cd98f00b204e9800998ecf8427e',
            'size' => 1048576,
            'lastModified' => '2026-07-30T03:00:00Z',
        ],
        [
            'filename' => 'blazemedia-category-report-20260730.tsv.gz',
            'md5' => '5d41402abc4b2a76b9719d911017c592',
            'size' => 2097152,
            'lastModified' => '2026-07-30T03:05:00Z',
        ],
    ],
];

test('listReports colpisce /reports/v1/listReports senza body', function () use ($listReportsPayload) {
    $client = mockedCreatorsClient([jsonStubResponse(200, $listReportsPayload)], $history);

    $response = $client->listReports();

    $request = lastMockRequest($history);

    expect($request->getMethod())->toBe('POST');
    expect($request->getUri()->getPath())->toBe('/reports/v1/listReports');
    expect((string) $request->getBody())->toBe('');
    expect($response['reports'])->toHaveCount(2);
})->group('unit');

test('listReports invia marketplace e bearer token', function () use ($listReportsPayload) {
    $client = mockedCreatorsClient([jsonStubResponse(200, $listReportsPayload)], $history);

    $client->listReports();

    $request = lastMockRequest($history);

    expect($request->getHeaderLine('x-marketplace'))->toBe('www.amazon.it');
    expect($request->getHeaderLine('Authorization'))->toBe('Bearer stub-access-token, Version 2.2');
})->group('unit');

test('getReport invia il filename e restituisce la presigned url', function () {
    $client = mockedCreatorsClient([
        jsonStubResponse(200, ['url' => 'https://creatorsapi-reports.example.invalid/file.tsv.gz?sig=stub']),
    ], $history);

    $response = $client->getReport('blazemedia-tracking_id-report-20260730.tsv.gz');

    $request = lastMockRequest($history);
    $body = json_decode((string) $request->getBody(), true);

    expect($request->getUri()->getPath())->toBe('/reports/v1/getReport');
    expect($body['filename'])->toBe('blazemedia-tracking_id-report-20260730.tsv.gz');
    expect($response['url'])->toContain('.tsv.gz');
})->group('unit');

test('getReport rifiuta un filename vuoto senza chiamare la rete', function () {
    $client = mockedCreatorsClient([], $history);

    expect(fn () => $client->getReport(''))
        ->toThrow(InvalidArgumentException::class);
})->group('unit');
