<?php

namespace Tests\Feature\Api\V1\FullSurface;

use Tests\Feature\Api\V1\FullSurface\Support\FullSurfaceE2EContractCase;

class ApiBatch13PaymentProviderLedgerReconciliationContractTest extends FullSurfaceE2EContractCase
{
    public function test_payment_provider_payloads_do_not_bypass_ledger_validation(): void
    {
        $routes = $this->apiRoutesContainingAny(['paypal', 'stripe', 'payment', 'transaction', 'ledger', 'receipt', 'invoice']);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            if (! in_array($method, ['POST', 'PUT', 'PATCH'], true)) {
                continue;
            }

            $payload = $this->payloadFor($method, $route->uri()) + [
                'provider' => 'paypal',
                'provider_transaction_id' => 'BATCH13-LEDGER-REPLAY',
                'transaction_id' => 'BATCH13-LEDGER-REPLAY',
                'external_id' => 'BATCH13-LEDGER-REPLAY',
                'amount' => '25.00',
                'currency' => 'USD',
                'status' => 'completed',
                'invoice_id' => $this->ids['invoiceId'],
                'parent_id' => $this->ids['parentId'],
                'student_id' => $this->ids['studentId'],
                'metadata' => [
                    'invoice_id' => $this->ids['invoiceId'],
                    'amount' => '999999999999.99',
                    'currency' => 'XXX',
                ],
            ];

            $response = $this->requestAs($this->admin, $method, $route->uri(), $payload);
            $this->assertControlled($response, $method, $route->uri());
            $this->assertStringNotContainsString('SQLSTATE', $response->getContent());
            $this->assertStringNotContainsString('ledger imbalance', strtolower($response->getContent()));
        }
    }

    public function test_duplicate_provider_reference_is_controlled_across_payment_routes(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['payment', 'transaction', 'paypal', 'stripe']), 0, 25);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            if (! in_array($method, ['POST', 'PUT', 'PATCH'], true)) {
                continue;
            }

            $payload = $this->payloadFor($method, $route->uri()) + [
                'provider_reference' => 'BATCH13-DUPLICATE-PROVIDER-REFERENCE',
                'transaction_id' => 'BATCH13-DUPLICATE-PROVIDER-REFERENCE',
                'idempotency_key' => 'BATCH13-DUPLICATE-PROVIDER-REFERENCE',
            ];

            $first = $this->requestAs($this->admin, $method, $route->uri(), $payload);
            $second = $this->requestAs($this->admin, $method, $route->uri(), $payload);

            $this->assertControlled($first, $method, $route->uri());
            $this->assertControlled($second, $method, $route->uri());
            $this->assertNotContains($second->getStatusCode(), [500, 501, 502, 503]);
        }
    }
}
