<?php

declare(strict_types=1);

namespace App\Core;

class Router
{
    private array $routes = [];

    public function __construct(
        private Request $request,
        private Response $response
    ) {
    }

    public function get(string $path, array|callable|string $callback): void
    {
        $this->routes['get'][$path] = $callback;
    }

    public function post(string $path, array|callable|string $callback): void
    {
        $this->routes['post'][$path] = $callback;
    }

    public function resolve(): string
    {
        $path = $this->request->path();
        $method = $this->request->method();
        $callback = $this->routes[$method][$path] ?? false;

        if (!$callback) {
            $this->response->setStatusCode(404);
            return View::render('errors/404');
        }

        if (is_string($callback)) {
            return View::render($callback);
        }

        if (is_array($callback)) {
            $controller = new $callback[0]();
            $callback[0] = $controller;
        }

        return (string) call_user_func($callback, $this->request, $this->response);
    }
}
