<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Support\ApiResponse;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;

final class JwtAuthenticate
{
    public function handle(Request $request, Closure $next): Response
    {
        try {
            $user = JWTAuth::parseToken()->authenticate();
        } catch (JWTException) {
            return ApiResponse::error('登录令牌无效', 401, 401);
        }

        if (! $user || ! $user->is_active) {
            return ApiResponse::error('账号不可用', 401, 401);
        }

        auth()->setUser($user);
        auth('api')->setUser($user);
        $request->setUserResolver(fn () => $user);

        return $next($request);
    }
}
