<?php

namespace App\Domains\Auth\Http\Middleware;

use Closure;
use ReflectionClass;
use ReflectionMethod;
use Illuminate\Http\Request;
use App\Exceptions\AuthException;
use App\Exceptions\NotExistException;
use App\Domains\Auth\Services\AuthService;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class AdminAuthenticate
{
    public function handle(Request $request, Closure $next)
    {
        $auth  = app('auth:admin')->getGuard();

        if (! $auth->parser()->setRequest($request)->hasToken()) {
            throw new AuthException('未提供Token', AuthException::TOKEN_NOT_PROVIDED);
        }

        try {
            if (! $account = app('auth:admin')->authenticate()) {
                throw new AuthException('账号未登录', AuthException::NOT_LOGIN);
            }
        } catch (JWTException $e) {
            throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
        }
        
        $checks = app()->tagged('auth:admin:check');

        foreach ($checks as $check) {
            call_user_func_array([$check, 'handle'], ['account' => $account, 'request' => $request]);
        }

        $response = $next($request);

        $token =  app('auth:admin')->getToken();

        $response->headers->set('Authorization', 'Bearer '.$token);

        return $response;
    }
}
