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

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

export type ResuestRefreshToken = {
  code: number;
  data: ReqRefreshToken | null;
  msg: string;
  config: InternalAxiosRequestConfig<any>;
};

/** 刷新token的队列 */
let refreshList: ((config: ResuestRefreshToken) => void)[] = [];
/** 是否正在刷新 */
let refreshing = false;

/**
 * 刷新
 */
export function requestRefreshTokenFun(config: InternalAxiosRequestConfig<any>, refreshToken: string): Promise<ResuestRefreshToken> {
  return new Promise<ResuestRefreshToken>((resolve, reject) => {
    refreshList.push((res) => {
      res.code === 200 ? resolve(res) : reject(res);
    });
    if (!refreshing) {
      refreshing = true;
      _refreshTokenFun(refreshToken)
        .then((res) => {
          refreshList.forEach((cb) => {
            cb({ code: 200, data: res.data, msg: '', config });
          });
          refreshing = false;
          refreshList = [];
        })
        .catch(() => {
          refreshList.forEach((cb) => {
            cb({ code: 40003, data: null, msg: '代码错误，SX2005', config });
          });
          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: '代码错误，SX2006' });
  }
}
