<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiUnicodeNormalizationAndInputContractTest extends FullSurfaceE2EContractCase
{
    public function test_text_inputs_accept_or_reject_unicode_cleanly_without_corrupting_json(): void
    {
        $routes = array_slice(array_filter($this->apiRoutes(), fn ($route) => in_array($this->primaryMethod($route), ['POST', 'PUT', 'PATCH'], true)), 0, 100);
        $text = "Arabic العربية Hebrew עברית emoji 😀 combined e\u{0301} zero-width\u{200B} text";

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            $uri = $route->uri();
            $response = $this->requestAs($this->actorFor($uri), $method, $uri, $this->payloadFor($method, $uri) + [
                'name' => $text,
                'title' => $text,
                'description' => $text,
                'notes' => $text,
                'message' => $text,
            ]);

            $this->assertControlled($response, $method, $uri);
            $this->assertNoServerError($response, 'unicode input at ' . $method . ' ' . $uri);

            if ($response->getContent() !== '') {
                $this->assertTrue($this->isJsonString($response->getContent()) || ! str_contains((string) $response->headers->get('Content-Type'), 'json'), $uri . ' must not emit broken JSON for unicode input.');
            }
        }
    }

    public function test_emails_and_phone_fields_reject_visually_confusable_values_cleanly(): void
    {
        $routes = $this->apiRoutesContainingAny(['users', 'parents', 'guardian', 'authorized', 'contact', 'support', 'messages', 'whatsapp']);

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

            $uri = $route->uri();
            $response = $this->requestAs($this->actorFor($uri), $method, $uri, $this->payloadFor($method, $uri) + [
                'email' => "admin\u{202E}@example.test",
                'phone' => "+1\u{202E}5551234567",
            ]);

            $this->assertControlled($response, $method, $uri);
            $this->assertNoServerError($response, 'confusable email/phone at ' . $method . ' ' . $uri);
        }
    }
}
