<?php

declare(strict_types=1);

namespace TekDek\Employees;

/**
 * Minimal router for the employees API.
 */
class Router
{
    /**
     * Dispatch the current request to the appropriate controller method.
     */
    public static function dispatch(?EmployeeController $controller = null): void
    {
        $controller = $controller ?? new EmployeeController();

        // Set common headers
        header('Content-Type: application/json; charset=utf-8');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Accept');
        header('Cache-Control: public, max-age=300, s-maxage=600');
        header('X-Content-Type-Options: nosniff');

        // Handle CORS preflight
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            http_response_code(204);
            return;
        }

        // Only allow GET
        if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
            http_response_code(405);
            echo json_encode([
                'success' => false,
                'error'   => 'Method not allowed. Use GET.',
            ]);
            return;
        }

        // Parse the URI path
        $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $uri = rtrim($uri, '/');

        // Route: GET /api/employees
        if ($uri === '/api/employees') {
            $controller->index();
            return;
        }

        // Route: GET /api/employees/:slug
        if (preg_match('#^/api/employees/([a-z0-9-]+)$#', $uri, $matches)) {
            $controller->show($matches[1]);
            return;
        }

        // 404 — no matching route
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'error'   => 'Endpoint not found.',
        ]);
    }
}
