import axios from "axios";
import { createLog } from "./logger";

export async function tryLimit({ action, limit = 100 }) {
  let res = null;
  let serverPass = false;
  try {
    res = await axios.get(
      `https://tcc.qmth.com.cn/rate_limit/prod/${action}/${limit}`,
      { timeout: 10 * 1000 }
    );
    serverPass = res.data.pass;

    createLog({
      action: "第一次限流调用",
      limitAction: action,
      detail: serverPass ? "进入" : "限流",
    });
    if (!serverPass) {
      // 休眠 1 ~ 5 秒 再试
      res = null; // 供外部判断

      const sleepTime = Math.random() * 4 + 1;
      console.log({ sleepTime, now: Date.now() });
      await new Promise((resolve) => setTimeout(resolve, sleepTime * 1000));
      console.log({ sleepTime, now: Date.now() });
      res = await axios.get(
        `https://tcc.qmth.com.cn/rate_limit/prod/${action}/${limit}`,
        { timeout: 10 * 1000 }
      );
      serverPass = res.data.pass;
      createLog({
        action: "限流后自动重试",
        limitAction: action,
        detail: serverPass ? "进入" : "依然限流",
      });
    }
  } catch (error) {
    console.log(error);
    window._hmt.push(["_trackEvent", action, "获取rateLimit失败"]);
  }

  return { limitResult: serverPass, serverOk: !!res };
}
