import { LIMIT_SERVER } from "@/constants/constants";
import axios from "axios";

/** 是否对请求限流 */
export async function tryLimit({
  action,
  limit = 100,
}: {
  action: string;
  limit: number;
}) {
  let res = null;
  let serverPass = false;
  try {
    res = await axios.get(
      `${LIMIT_SERVER}/rate_limit/prod/${action}/${limit}`,
      { timeout: 10 * 1000 }
    );
    serverPass = res.data.pass;

    logger({
      key: "请求限流",
      cnl: ["server"],
      act: "第一次限流调用",
      dtl: serverPass ? "进入" : "限流",
      ext: { limitAction: action },
    });
    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(
        `${LIMIT_SERVER}/rate_limit/prod/${action}/${limit}`,
        { timeout: 10 * 1000 }
      );
      serverPass = res.data.pass;
      logger({
        key: "请求限流",
        cnl: ["server"],
        act: "限流后自动重试",
        dtl: serverPass ? "进入" : "依然限流",
        ext: { limitAction: action },
      });
    }
  } catch (error) {
    console.log(error);
    logger({
      key: "请求限流",
      cnl: ["server"],
      act: "限流请求失败",
      ejn: JSON.stringify(error),
      ext: { limitAction: action },
    });
  }

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