<?php
declare(strict_types=1);

namespace App\Core;

final class Router
{
    /** @var array<int, array{method:string,pattern:string,handler:callable|array,auth:bool}> */
    private array $routes = [];

    public function get(string $path, callable|array $handler, bool $auth = true): self
    {
        return $this->add('GET', $path, $handler, $auth);
    }

    public function post(string $path, callable|array $handler, bool $auth = true): self
    {
        return $this->add('POST', $path, $handler, $auth);
    }

    private function add(string $method, string $path, callable|array $handler, bool $auth): self
    {
        $this->routes[] = [
            'method' => $method,
            'pattern' => $this->compile($path),
            'handler' => $handler,
            'auth' => $auth,
        ];
        return $this;
    }

    private function compile(string $path): string
    {
        $path = '/' . trim($path, '/');
        if ($path === '/') {
            return '#^/$#';
        }
        $regex = preg_replace('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', '(?P<$1>[^/]+)', $path);
        return '#^' . $regex . '$#';
    }

    public function dispatch(Request $request): void
    {
        foreach ($this->routes as $route) {
            if ($route['method'] !== $request->method()) {
                continue;
            }
            if (!preg_match($route['pattern'], $request->path(), $matches)) {
                continue;
            }
            $params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
            $request->setParams($params);

            if ($route['auth'] && !Auth::instance()->check()) {
                if (is_ajax()) {
                    json_out(['ok' => false, 'error' => 'Unauthorized'], 401);
                }
                redirect('login');
            }

            $handler = $route['handler'];
            if (is_array($handler)) {
                [$class, $method] = $handler;
                $controller = new $class();
                $controller->{$method}($request);
                return;
            }
            $handler($request);
            return;
        }

        http_response_code(404);
        if (is_ajax()) {
            json_out(['ok' => false, 'error' => 'Not found'], 404);
        }
        if (Auth::instance()->check()) {
            view('errors/404', ['title' => 'Not found']);
            return;
        }
        echo 'Not found';
    }
}
