<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiBatch12FinancialLedgerIntegrityContractTest extends FullSurfaceE2EContractCase
{
    public function test_financial_mutations_reject_ledger_breaking_amounts_and_cross_invoice_ids(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['finance', 'invoice', 'payment', 'refund', 'charge', 'installment', 'fee']), 0, 150);
        $amounts = ['-0.01', '-999999', '999999999999999999999', '1e309', 'NaN', 'Infinity', '0.00000001'];

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

            foreach ($amounts as $amount) {
                $response = $this->requestAs($this->actorFor($route->uri()), $method, $route->uri(), $this->payloadFor($method, $route->uri()) + [
                    'amount' => $amount,
                    'paid_amount' => $amount,
                    'balance' => $amount,
                    'invoice_id' => $this->ids['studentId'],
                ]);

                $this->assertControlled($response, $method, $route->uri());
                $this->assertNoServerError($response, 'financial ledger boundary '.$method.' '.$route->uri());
                $this->assertStringNotContainsString('SQLSTATE', $response->getContent(), 'financial route leaked SQL');
            }
        }
    }

    public function test_parent_cannot_force_finance_scope_to_all_families(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['invoice', 'payment', 'finance', 'receipt', 'balance']), 0, 100);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            $response = $this->requestAs($this->parent, $method, $route->uri(), $this->payloadFor($method, $route->uri()) + [
                'scope' => 'all',
                'parent_id' => $this->ids['parentId'] + 777,
                'include_voided' => true,
            ]);

            $this->assertControlled($response, $method, $route->uri());
            $this->assertNoServerError($response, 'parent finance scope override '.$method.' '.$route->uri());
        }
    }
}
