<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiEnumAndStateMachineContractTest extends FullSurfaceE2EContractCase
{
    public function test_status_fields_reject_unknown_states_without_defaulting_to_success(): void
    {
        $routes = $this->apiRoutesContainingAny(['attendance', 'invoice', 'payment', 'refund', 'support', 'message', 'inventory', 'promotion', 'school-year']);
        $states = ['approved_by_accident', 'null', '', 'DROP TABLE', 'deleted-but-visible', 'paid_and_refunded'];

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

            foreach ($states as $state) {
                $uri = $route->uri();
                $response = $this->requestAs($this->actorFor($uri), $method, $uri, $this->payloadFor($method, $uri) + ['status' => $state, 'state' => $state]);

                $this->assertControlled($response, $method, $uri);
                $this->assertNoServerError($response, 'unknown status ' . $state . ' at ' . $method . ' ' . $uri);
            }
        }
    }

    public function test_terminal_states_are_not_reopened_by_low_privilege_users(): void
    {
        $routes = $this->apiRoutesContainingAny(['reopen', 'restore', 'unarchive', 'cancel', 'void', 'resolve']);

        foreach (array_slice($routes, 0, 80) as $route) {
            $method = $this->primaryMethod($route);
            $uri = $route->uri();

            $response = $this->requestAs($this->parent, $method, $uri, $this->payloadFor($method, $uri));

            $this->assertStatusIn($response, [400, 401, 403, 404, 405, 409, 419, 422], 'low privilege terminal state transition ' . $method . ' ' . $uri);
            $this->assertNoServerError($response, 'low privilege terminal state transition ' . $method . ' ' . $uri);
        }
    }
}
