<?php

namespace App\Http\Middleware;

use App\Auth\Clock;
use App\Auth\SessionRepository;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AuthMiddleware
{
    public const COOKIE_NAME = 'auth_token';

    public function __construct(
        private SessionRepository $sessionRepo,
        private Clock $clock,
    ) {}

    /**
     * @param  Closure(Request): Response  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $token = $request->cookie(self::COOKIE_NAME);
        if (! is_string($token) || $token === '') {
            return $this->unauthorized();
        }

        $session = $this->sessionRepo->findByToken($token);
        if ($session === null) {
            return $this->unauthorized();
        }

        if ($session->isExpired($this->clock->now())) {
            $this->sessionRepo->deleteByToken($token);

            return $this->unauthorized();
        }

        $request->attributes->set('user', $session->getUser());

        return $next($request);
    }

    private function unauthorized(): JsonResponse
    {
        return new JsonResponse(['error' => 'unauthenticated'], 401);
    }
}
