<?php

namespace Modules\SystemUser\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Modules\SystemUser\Models\SysAccessToken;
use Symfony\Component\HttpFoundation\Response;

class AuthGuardMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param Closure(Request): (Response) $next
     */
    public function handle(Request $request, Closure $next, ...$guards): Response
    {
        $token = $request->bearerToken();
        if (!$token) {
            return response()->json(['msg' => 'Token not provided', 'success' => false], 401);
        }
        // 查找 token
        $accessToken = SysAccessToken::findToken($token);
        if (!$accessToken) {
            return response()->json(['msg' => 'Invalid token', 'success' => false], 401);
        }
        if (empty($guards)) {
            $guards = ['sys_users'];
        }
        Log::info('Guards: ',  $guards);
        Log::info('Auth Providers: ',  config('auth.providers'));
        foreach ($guards as $guard) {
            Log::info('Auth Providers Model: ' . config('auth.providers.' . $guard . '.model'));
            if ($accessToken->tokenable_type == config('auth.providers.' . $guard . '.model')) {
                return $next($request);
            }
        }
        return response()->json([
            'msg' => __('user.not_login'),
            'success' => false
        ], 401);
    }
}
