<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiReportMathAndFinancialInvariantContractTest extends FullSurfaceE2EContractCase
{
    public function test_financial_endpoints_reject_non_decimal_and_currency_confusion_inputs(): void
    {
        $routes = $this->apiRoutesContainingAny(['finance', 'invoice', 'payment', 'refund', 'fee', 'charge', 'installment']);
        $amounts = ['25,00', '$25.00', '1e309', '0x10', '--25', '25 USD'];

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

            foreach ($amounts as $amount) {
                $uri = $route->uri();
                $response = $this->requestAs($this->admin, $method, $uri, $this->payloadFor($method, $uri) + ['amount' => $amount, 'total' => $amount, 'balance' => $amount]);

                $this->assertControlled($response, $method, $uri);
                $this->assertNoServerError($response, 'bad financial amount ' . $amount . ' for ' . $method . ' ' . $uri);
            }
        }
    }

    public function test_report_filters_do_not_create_negative_or_impossible_aggregation_windows(): void
    {
        $routes = $this->apiRoutesContainingAny(['report', 'summary', 'dashboard', 'analytics', 'finance']);

        foreach (array_slice($routes, 0, 100) as $route) {
            if ($this->primaryMethod($route) !== 'GET') {
                continue;
            }

            $uri = $route->uri();
            $response = $this->actingAs($this->actorFor($uri), 'api')->getJson($this->materializePath($uri) . '?' . http_build_query([
                'from' => '2026-12-31',
                'to' => '2025-01-01',
                'group_by' => 'parent.password',
                'aggregate' => 'sum(password)',
                'school_year' => '../../../../.env',
            ]));

            $this->assertControlled($response, 'GET', $uri);
            $this->assertNoServerError($response, 'bad report aggregation query at ' . $uri);
            $this->assertStringNotContainsStringIgnoringCase('password', $response->getContent(), $uri . ' must not echo sensitive aggregate fields.');
        }
    }
}
