<?php
declare (strict_types=1);

namespace app\middleware;

use think\facade\Cache;
use think\facade\Lang;

class CheckApi
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $header = $request->header();
        $lang = $header['schedule-lang'] ?? 'en';
        Lang::setLangSet($lang);
        $user = [];
        if (empty($header['debug-schedule-2023'])) {
            $time = $header['s-time'] ?? '';
            $authorization = $header['authorization'] ?? '';
            $token = strtolower($header['s-token'] ?? '');
            if (!$time || !$token) {
                return json(['success' => false, 'msg' => Lang::get('没有权限')]);
            }
            $check_token = md5($time . '@62b7c5572a99ee1@' . $time);
            if ($token !== $check_token) {
                return json(['success' => false, 'msg' => Lang::get('没有权限') . ' _1']);
            }
            if (!in_array($request->pathinfo(), ['login', 'register', 'getAgreement', 'getConfig', 'getHotPro'])) {
                if (!$authorization) {
                    return json(['success' => false, 'msg' => Lang::get('没有权限') . ' _2']);
                }
                $user = Cache::get($authorization);
                if (empty($user)) {
                    return json(['success' => false, 'msg' => Lang::get('登录失效，请重新登录'), 'logout' => true]);
                }
            }
        } else {
            $user = [
                'id' => $header['s-uid'] ?? 1,
                'username' => '1888888888',
                'nickname' => '测试',
                'invite_code' => 'qEk8ik',
                'auth' => 'f75ccb8cb730466f1049ec51cb317782',
            ];
        }
        $request->user = $user;
        $response = $next($request);
        return $response;
    }
}
