<?php

namespace App\Http\Middleware;

use App\Enums\KeyValue;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureTokenIsValid
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (! session()->has(KeyValue::TOKEN_API->value)) {
            if ($request->ajax()) {
                return response('Unauthorized', 401);
            }

            return redirect()->guest('/oauth/login');
        }

        return $next($request);
    }
}
