<?php

declare(strict_types=1);

namespace BotGuard\Middleware;

use BotGuard\Core\Auth;
use BotGuard\Core\Request;
use BotGuard\Core\Response;
use BotGuard\Core\Session;
use Closure;

/**
 * Requires an authenticated user; redirects guests to the login page.
 *
 * Registered under the alias "auth" in the Kernel's middleware map.
 */
final class AuthMiddleware implements MiddlewareInterface
{
    public function __construct(private Auth $auth, private Session $session)
    {
    }

    public function handle(Request $request, Closure $next): Response
    {
        if ($this->auth->guest()) {
            if ($request->wantsJson()) {
                return Response::json(['error' => 'Unauthenticated.'], 401);
            }

            $this->session->flash('error', 'Please sign in to continue.');
            $this->session->put('__intended_url', $request->path());

            return Response::redirect('/login');
        }

        return $next($request);
    }
}
