import { ref } from 'vue';
import { defineStore } from 'pinia';
import type { AxiosRequestConfig } from 'axios';
import { SetupStoreId } from '@/enum';

interface FailedRequest {
  config: AxiosRequestConfig;
  resolve: (value: any) => void;
  reject: (reason: any) => void;
}

export const useReauthStore = defineStore(SetupStoreId.Reauth, () => {
  const isReauthenticating = ref(false);
  const failedRequestsQueue = ref<FailedRequest[]>([]);

  /**
   * 添加失败的请求到队列
   */
  function addFailedRequest(config: AxiosRequestConfig, resolve: (value: any) => void, reject: (reason: any) => void) {
    failedRequestsQueue.value.push({ config, resolve, reject });
  }

  /**
   * 开始重新认证流程
   */
  function startReauth() {
    isReauthenticating.value = true;
  }

    /**
   * 重新认证成功，重新发送所有失败的请求
   */
  function reauthSuccess() {
    isReauthenticating.value = false;

    // 重新发送所有失败的请求
    failedRequestsQueue.value.forEach(async ({ config, resolve, reject }) => {
      try {
        // 动态导入axios来重新发送请求
        const axios = await import('axios');

        // 更新token
        const token = localStorage.getItem('token');
        if (token && config.headers) {
          config.headers['Authorization'] = `Bearer ${token}`;
        }

        // 重新发送请求
        const response = await axios.default.request(config);
        resolve(response);
      } catch (error) {
        reject(error);
      }
    });

    failedRequestsQueue.value = [];
  }

  /**
   * 重新认证失败，拒绝所有失败的请求
   */
  function reauthFailed() {
    isReauthenticating.value = false;

    // 拒绝所有失败的请求
    failedRequestsQueue.value.forEach(({ reject }) => {
      reject(new Error('Authentication failed'));
    });

    failedRequestsQueue.value = [];
  }

  /**
   * 重置状态
   */
  function reset() {
    isReauthenticating.value = false;
    failedRequestsQueue.value = [];
  }

  return {
    isReauthenticating,
    failedRequestsQueue,
    addFailedRequest,
    startReauth,
    reauthSuccess,
    reauthFailed,
    reset
  };
});
