/**
 * 主要用于请求后置拦截,后置刷新token
 * 主要用于请求后置拦截,后置刷新token
 */

import { type ReqRefreshToken, refreshTokenAxios } from '@/api/login';
import type { Response } from '@/utils/axios/axios';

/** 刷新token的队列 */
let refreshList: ((res: Response<ReqRefreshToken | null>) => void)[] = [];
/** 是否正在刷新 */
let refreshing = false;

/**
 * 刷新
 */
export function responseRefreshTokenFun(refreshToken: string): Promise<Response<ReqRefreshToken>> {
  return new Promise<Response<ReqRefreshToken>>((resolve, reject) => {
    refreshList.push((res) => {
      res.code === 200 ? resolve(res as Response<ReqRefreshToken>) : reject(res);
    });
    if (!refreshing) {
      refreshing = true;
      _refreshTokenFun(refreshToken)
        .then((res) => {
          refreshList.forEach((cb) => {
            cb(res);
          });
          refreshing = false;
          refreshList = [];
        })
        .catch(() => {
          refreshList.forEach((cb) => {
            cb({ code: 40003, data: null, msg: '代码错误，SX2004' });
          });
          refreshing = false;
          refreshList = [];
        });
    }
  });
}

/**
 * 自动登录
 */
async function _refreshTokenFun(refreshToken: string): Promise<Response<ReqRefreshToken>> {
  try {
    const res = await refreshTokenAxios(refreshToken);
    return Promise.resolve({ code: 200, data: res.data, msg: '' });
    // oxlint-disable-next-line no-unused-vars
  } catch (error: any) {
    return Promise.reject({ code: 40003, msg: '代码错误，SX2003' });
  }
}
