<?php
declare(strict_types=1);

namespace Tests\Unit\Api;

use Tests\TestCase;
use App\Core\App;
use App\Core\Router;

final class ApiRoutingTest extends TestCase
{
    public function testApiRoutesFileStructure(): void
    {
        $basePath = dirname(__DIR__, 3);

        $authRoutes = require $basePath . '/app/Modules/Auth/ApiRoutes.php';
        $this->assertIsArray($authRoutes);
        $this->assertNotEmpty($authRoutes);

        foreach ($authRoutes as $route) {
            $this->assertIsArray($route);
            $this->assertGreaterThanOrEqual(3, count($route));
            $this->assertContains($route[0], ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);
            $this->assertStringStartsWith('/api/v1/', $route[1]);
        }
    }

    public function testMemberApiRoutesFile(): void
    {
        $basePath = dirname(__DIR__, 3);

        $routes = require $basePath . '/app/Modules/Members/ApiRoutes.php';
        $this->assertIsArray($routes);

        $paths = array_column($routes, 1);
        $this->assertContains('/api/v1/members', $paths);
        $this->assertContains('/api/v1/members/{id:\d+}', $paths);
        $this->assertContains('/api/v1/members/search', $paths);
    }

    public function testPaymentApiRoutesFile(): void
    {
        $basePath = dirname(__DIR__, 3);

        $routes = require $basePath . '/app/Modules/Payments/ApiRoutes.php';
        $this->assertIsArray($routes);

        $paths = array_column($routes, 1);
        $this->assertContains('/api/v1/payments', $paths);
        $this->assertContains('/api/v1/payments/{id:\d+}', $paths);
    }

    public function testAllApiRoutesHaveCorsMiddleware(): void
    {
        $basePath = dirname(__DIR__, 3);
        $files = glob($basePath . '/app/Modules/*/ApiRoutes.php');

        foreach ($files as $file) {
            $routes = require $file;
            foreach ($routes as $route) {
                $middleware = $route[3] ?? [];
                $this->assertContains('cors', $middleware, "Route {$route[1]} in {$file} missing cors middleware");
            }
        }
    }

    public function testRouterRegistersApiRoutes(): void
    {
        $router = new Router();

        $basePath = dirname(__DIR__, 3);
        $files = glob($basePath . '/app/Modules/*/ApiRoutes.php');

        $routeCount = 0;
        foreach ($files as $file) {
            $routes = require $file;
            foreach ($routes as $route) {
                $router->addRoute($route[0], $route[1], $route[2], $route[3] ?? [], $route[4] ?? null);
                $routeCount++;
            }
        }

        $this->assertGreaterThanOrEqual(7, $routeCount);
    }
}
