<?php

declare(strict_types=1);

namespace Lab;

final class Router
{
    /** @var array<string, array<string, callable>> */
    private array $routes = [];

    public function get(string $path, callable $handler): void
    {
        $this->routes['GET'][$this->normalize($path)] = $handler;
    }

    public function post(string $path, callable $handler): void
    {
        $this->routes['POST'][$this->normalize($path)] = $handler;
    }

    public function dispatch(string $method, string $uri): void
    {
        $path = $this->normalize($uri);
        $handler = $this->routes[$method][$path] ?? null;
        if ($handler === null) {
            if (str_starts_with($path, '/api/')) {
                Helpers::json(['ok' => false, 'error' => 'Not found'], 404);
            }
            http_response_code(404);
            View::render('errors/404', ['title' => 'Δεν βρέθηκε']);

            return;
        }
        $handler();
    }

    private function normalize(string $path): string
    {
        $path = '/' . trim($path, '/');

        return $path === '/' ? '/' : rtrim($path, '/');
    }
}
