<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiSchemaKeyStabilityExpansionContractTest extends FullSurfaceE2EContractCase
{
    public function test_core_resource_success_payloads_keep_identity_and_display_keys(): void
    {
        $contracts = [
            'api/v1/users' => ['id', 'email', 'firstname', 'lastname'],
            'api/v1/students' => ['id', 'firstname', 'lastname', 'parent_id'],
            'api/v1/classes' => ['id', 'name'],
            'api/v1/class-sections' => ['id', 'class_section_id', 'class_section_name'],
            'api/v1/parent/profile' => ['id', 'email'],
            'api/v1/teacher/classes' => ['class_section_id', 'class_section_name'],
            'api/v1/finance/invoices' => ['id', 'invoice_id', 'amount', 'balance'],
            'api/v1/inventory/items' => ['id', 'name', 'quantity'],
            'api/v1/messages' => ['id', 'subject', 'message', 'body'],
            'api/v1/support/tickets' => ['id', 'subject', 'status'],
        ];

        foreach ($contracts as $uri => $expectedAnyKeys) {
            $response = $this->requestAs($this->actorFor($uri), 'GET', $uri);
            $this->assertNoServerError($response, 'GET ' . $uri);

            if ($response->getStatusCode() !== 200 || ! $this->isJsonString($response->getContent())) {
                continue;
            }

            $payload = $this->flattenKeys($response->json());
            $this->assertTrue(
                count(array_intersect($expectedAnyKeys, $payload)) > 0,
                $uri . ' should expose at least one stable identity/display key. Keys: ' . implode(', ', $payload)
            );
        }
    }

    public function test_error_payloads_keep_client_actionable_fields(): void
    {
        foreach ($this->apiRoutes() 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, ['force_validation_failure' => true]);
            $this->assertNoServerError($response, "$method $uri");

            if (in_array($response->getStatusCode(), [400, 401, 403, 404, 409, 419, 422], true) && $this->isJsonString($response->getContent())) {
                $keys = $this->flattenKeys($response->json());
                $this->assertTrue(
                    count(array_intersect(['message', 'errors', 'error', 'ok', 'status'], $keys)) > 0,
                    "$method $uri must return an actionable error envelope. Keys: " . implode(', ', $keys)
                );
            }
        }
    }

    /** @return list<string> */
    private function flattenKeys(mixed $payload, string $prefix = ''): array
    {
        if (! is_array($payload)) {
            return [];
        }

        $keys = [];
        foreach ($payload as $key => $value) {
            if (is_string($key)) {
                $keys[] = $key;
                if (is_array($value)) {
                    $keys = array_merge($keys, $this->flattenKeys($value, $prefix . $key . '.'));
                }
            } elseif (is_array($value)) {
                $keys = array_merge($keys, $this->flattenKeys($value, $prefix));
            }
        }

        return array_values(array_unique($keys));
    }
}
