import axios from 'axios';
import type { AxiosError, AxiosResponse } from 'axios';
import { useReauthStore } from '@/store/modules/reauth';

/**
 * 处理401错误的通用函数
 */
export function handle401Error(error: AxiosError): Promise<any> {
  const reauthStore = useReauthStore();

  console.warn('Global 401 Unauthorized - showing reauth modal');

  // 如果还没有在重新认证中，则开始重新认证流程
  if (!reauthStore.isReauthenticating) {
    reauthStore.startReauth();
    window.$reauth?.show();
  }

  // 将失败的请求添加到队列中，等待重新认证后重试
  return new Promise((resolve, reject) => {
    reauthStore.addFailedRequest(error.config!, resolve, reject);
  });
}

/**
 * 设置全局axios拦截器
 */
export function setupGlobalAxiosInterceptor() {
  // 响应拦截器
  axios.interceptors.response.use(
    (response: AxiosResponse) => {
      // 正常响应直接返回
      return response;
    },
    (error: AxiosError) => {
      // 检查是否为401错误
      if (error.response?.status === 401) {
        return handle401Error(error);
      }

      // 其他错误正常抛出
      return Promise.reject(error);
    }
  );

  console.log('✅ Global axios interceptor for 401 handling has been set up');
}

/**
 * 为指定的axios实例添加401拦截器
 */
export function addAxios401Interceptor(axiosInstance: any) {
  axiosInstance.interceptors.response.use(
    (response: AxiosResponse) => response,
    (error: AxiosError) => {
      if (error.response?.status === 401) {
        return handle401Error(error);
      }
      return Promise.reject(error);
    }
  );
}

/**
 * 创建一个包含401处理的axios实例
 */
export function createAxiosWithAuth(config?: any) {
  const instance = axios.create(config);
  addAxios401Interceptor(instance);
  return instance;
}

/**
 * 手动触发401处理（用于fetch或其他HTTP客户端）
 */
export function trigger401Handler(requestConfig?: any) {
  const reauthStore = useReauthStore();

  console.warn('Manual 401 trigger - showing reauth modal');

  if (!reauthStore.isReauthenticating) {
    reauthStore.startReauth();
    window.$reauth?.show();
  }

  // 如果有请求配置，也加入队列
  if (requestConfig) {
    return new Promise((resolve, reject) => {
      reauthStore.addFailedRequest(requestConfig, resolve, reject);
    });
  }
}

/**
 * 全局fetch拦截器（实验性）
 */
export function setupGlobalFetchInterceptor() {
  const originalFetch = window.fetch;

  window.fetch = async (...args) => {
    try {
      const response = await originalFetch(...args);

      // 检查401错误
      if (response.status === 401) {
        console.warn('Global fetch 401 Unauthorized - showing reauth modal');

        const reauthStore = useReauthStore();

        if (!reauthStore.isReauthenticating) {
          reauthStore.startReauth();
          window.$reauth?.show();
        }

        // 为fetch创建一个promise队列处理
        return new Promise((resolve, reject) => {
          const requestConfig = {
            url: args[0],
            options: args[1]
          };
          reauthStore.addFailedRequest(requestConfig, resolve, reject);
        });
      }

      return response;
    } catch (error) {
      throw error;
    }
  };

  console.log('✅ Global fetch interceptor for 401 handling has been set up');
}
