<?php

namespace App\Http\Middleware;

use App\Listeners\IssueApiToken;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RefreshApiToken
{
    public function handle(Request $request, Closure $next): Response
    {
        if (!$request->user() || !session('api_token_id')) {
            return $next($request);
        }

        $token = $request->user()
            ->tokens()
            ->find(session('api_token_id'));

        // Refresh if expired or within 30 minutes of expiry
        if (!$token || $token->expires_at->subMinutes(30)->isPast()) {
            app(IssueApiToken::class)->createToken($request->user());
        }

        return $next($request);
    }
}
