<?php

/**
 * Middleware для аутентифікації
 *
 * @package Flowaxy\Interface\Http\Middleware
 * @version 1.0.0 Alpha prerelease
 */

declare(strict_types=1);

namespace Flowaxy\Interface\Http\Middleware;

use Flowaxy\Interface\Http\Request;
use Flowaxy\Interface\Http\Response;
use Flowaxy\Domain\User\Services\AuthenticationService;
use Flowaxy\Infrastructure\Persistence\Repositories\UserRepository;

final class AuthMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, callable $next)
    {
        $sessionToken = $request->get('token') ?? $_SESSION['user_token'] ?? null;

        $authService = new AuthenticationService(new UserRepository());
        $user = $authService->check($sessionToken);

        if ($user === null) {
            return new Response(['error' => 'Unauthorized'], 401);
        }

        // Пользователь аутентифицирован, передаем запрос дальше
        return $next($request);
    }
}
