<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiFrontendBackendContractParityTest extends FullSurfaceE2EContractCase
{
    public function test_frontend_identity_and_api_identity_do_not_drift_apart(): void
    {
        $paths = ['/api/v1/auth/me', '/api/user', '/api/me', '/user/me'];

        foreach ($paths as $path) {
            $response = $this->actingAs($this->admin, 'api')->getJson($path);

            $this->assertNoServerError($response, 'identity contract at ' . $path);

            if ($response->getStatusCode() === 200) {
                $body = $response->json();
                $this->assertIsArray($body, $path . ' should return an inspectable JSON identity payload.');
                $this->assertTrue(
                    data_get($body, 'user.email') !== null || data_get($body, 'email') !== null || data_get($body, 'data.email') !== null,
                    $path . ' should expose a stable user email for frontend identity hydration.'
                );
            }
        }
    }

    public function test_login_aliases_return_compatible_token_and_user_contracts(): void
    {
        $paths = ['/api/v1/auth/login', '/api/login', '/user/login'];

        foreach ($paths as $path) {
            $response = $this->postJson($path, [
                'email' => $this->admin->email,
                'password' => 'password',
            ]);

            $this->assertNoServerError($response, 'login alias at ' . $path);

            if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) {
                $this->assertTrue($response->json('token') !== null || $response->json('access_token') !== null, $path . ' must expose a token field.');
                $this->assertTrue($response->json('user') !== null || $response->json('data.user') !== null, $path . ' must expose a user object.');
            }
        }
    }

    public function test_frontend_bootstrap_routes_do_not_require_admin_privilege_when_they_are_identity_or_config_only(): void
    {
        $routes = $this->apiRoutesContainingAny(['frontend', 'bootstrap', 'navigation', 'menu', 'preferences']);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);

            if ($method !== 'GET') {
                continue;
            }

            $uri = $route->uri();
            $response = $this->actingAs($this->parent, 'api')->getJson($this->materializePath($uri));

            $this->assertControlled($response, 'GET', $uri);
            $this->assertNoServerError($response, 'frontend bootstrap route at ' . $uri);
        }
    }
}
