<?php

declare(strict_types=1);

namespace app\admin\middleware;

use app\common\exception\NotAuthApi;
use app\common\model\Token;
use app\common\traits\Auth as TraitsAuth;
use app\Request;
use think\Response;

class Auth
{
    use TraitsAuth;
    /**
     * 忽略登录
     *
     * @var array
     * @date 2023-01-07
     * @example
     * @author admin
     * @since 1.0.0
     */
    private $ignoreLogin = [
        'Login' => ['*'],
        'admin' => ['*'],
    ];

    /**
     * 处理请求
     *
     * @param \app\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle(Request $request, \Closure $next): Response
    {
        $this->request = $request;

        if ($this->isIgnoreLogin()) {
            return $next($request);
        }

        if ($request->isLogin()) {
            $user = $request->getCurrentUser();
            if ($user->user_admin) {
                return $next($request);
            }
        }

        $api = join('/', [
            $request->controller(),
            $request->action()
        ]);

        $token = Token::getCurrent();

        /**
         * 缓存接口权限验证
         */
        $validate = $this->validateApi($token->token_api);
        /**
         * 缓存权限验证不通过
         */
        if ($validate === false) {
            /**
             * 自定义验证权限
             * 如果验证通过刷新缓存接口
             */
            $validate = $this->validateUser();
            if ($validate) {
                Token::getCurrentUser()->login();
            }
        }
        /**
         * 权限验证通过
         */
        if ($validate) {
            return $next($request);
        }
        throw new NotAuthApi("未授权接口 [ $api ]", 1);
    }
}
