<?php
declare(strict_types=1);

namespace App\Modules\Auth;

use App\Core\Http\Request;
use App\Core\Http\Response;

final class AuthMiddleware
{
    public function __construct(private readonly AuthService $auth)
    {
    }

    public function __invoke(Request $request, callable $next): Response
    {
        if (!$this->auth->check()) {
            return Response::redirect('/login');
        }

        $result = $next($request);
        if ($result instanceof Response) {
            return $result;
        }

        if (is_array($result)) {
            return Response::json($result);
        }

        return Response::html((string) $result);
    }
}
