<?php

namespace Tests\Feature\Api\V1\FullSurface;

use Illuminate\Routing\Route as LaravelRoute;
use Tests\Feature\Api\V1\FullSurface\Support\FullSurfaceE2EContractCase;

class ApiRouteNamingVersioningAndHygieneTest extends FullSurfaceE2EContractCase
{
    public function test_api_routes_do_not_use_debug_or_temporary_names(): void
    {
        foreach ($this->apiRoutes() as $route) {
            $uri = $route->uri();
            $name = (string) $route->getName();

            $this->assertDoesNotMatchRegularExpression('/\b(test|tmp|temp|debug|foo|bar|todo|fixme|wip)\b/i', $uri, "Temporary/debug URI leaked: $uri");
            $this->assertDoesNotMatchRegularExpression('/\b(test|tmp|temp|debug|foo|bar|todo|fixme|wip)\b/i', $name, "Temporary/debug route name leaked: $name");
        }
    }

    public function test_versioned_api_routes_stay_inside_v1_or_documented_legacy_aliases(): void
    {
        foreach ($this->apiRoutes() as $route) {
            $uri = $route->uri();

            $this->assertTrue(
                str_starts_with($uri, 'api/v1/') || $this->isKnownUnversionedAlias($uri),
                "API route must be versioned or explicitly classified as legacy alias: $uri"
            );
        }
    }

    public function test_duplicate_uri_method_pairs_do_not_exist(): void
    {
        $seen = [];

        foreach ($this->apiRoutes() as $route) {
            $key = $this->primaryMethod($route) . ' ' . $route->uri();
            $this->assertArrayNotHasKey($key, $seen, "Duplicate API method/URI pair: $key");
            $seen[$key] = true;
        }
    }

    public function test_route_placeholders_use_consistent_identifier_names(): void
    {
        foreach ($this->apiRoutes() as $route) {
            preg_match_all('/\{([^}:?]+).*?\}/', $route->uri(), $matches);

            foreach ($matches[1] as $placeholder) {
                $this->assertDoesNotMatchRegularExpression('/^[a-z]$/', $placeholder, "Placeholder is too vague in {$route->uri()}");
                $this->assertDoesNotMatchRegularExpression('/thing|stuff|data|param|value/i', $placeholder, "Placeholder is semantically useless in {$route->uri()}");
            }
        }
    }

    private function isKnownUnversionedAlias(string $uri): bool
    {
        return preg_match('#^api/(login|register|logout|user|auth|docs|health|captcha|frontend|public|db-check|scan|scanner)#', $uri) === 1;
    }
}
