<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiBatch12ConsistencyUnderPartialPayloadContractTest extends FullSurfaceE2EContractCase
{
    public function test_patch_routes_do_not_null_identity_or_ownership_when_optional_fields_are_missing(): void
    {
        $routes = array_slice($this->apiRoutes(), 0, 250);

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

            $response = $this->requestAs($this->actorFor($route->uri()), $method, $route->uri(), ['notes' => 'partial batch 12 update']);
            $this->assertControlled($response, $method, $route->uri());
            $this->assertNoServerError($response, 'partial payload update '.$method.' '.$route->uri());

            if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) {
                $body = strtolower($response->getContent());
                $this->assertStringNotContainsString('"id":null', $body, 'successful partial update nulled id');
                $this->assertStringNotContainsString('"user_id":null', $body, 'successful partial update nulled owner');
            }
        }
    }

    public function test_post_routes_handle_sparse_payloads_as_validation_not_crashes(): void
    {
        $routes = array_slice($this->apiRoutes(), 0, 250);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            if ($method !== 'POST') {
                continue;
            }

            $response = $this->requestAs($this->actorFor($route->uri()), $method, $route->uri(), ['name' => null]);
            $this->assertControlled($response, $method, $route->uri());
            $this->assertNoServerError($response, 'sparse post payload '.$method.' '.$route->uri());
        }
    }
}
