import type { AxiosInstance, AxiosRequestConfig } from "axios"
import { createAxios, RefreshManager } from "@sud-web/http"
import { ElMessage } from "element-plus"
import { get } from "lodash-es"
import { refreshTokenApi } from "@/api/login"
import { redirectToLogin } from "@/utils/auth-redirect"

// 401 刷新：refreshTokenApi 自身带 config.enableRefresh = false，避免刷新接口再触发刷新
const refreshManager = new RefreshManager(refreshTokenApi, {
  onRefreshFail: () => redirectToLogin()
})

/** 创建请求实例 */
function createService() {
  // CSRF / Token 的请求头注入与响应回写走 @sud-web/http 内置默认方案，无需自定义 onRequest/onCsrfToken
  return createAxios({
    refreshManager,
    axiosConfig: {
      timeout: 30000,
      // baseURL 不设，统一走 vite 代理 /api
      data: {}
    },
    hooks: {
      // 默认成功响应处理（业务 code !== 0）时的错误提示
      showErrorMessage(msg: string) {
        ElMessage.error(msg || "接口错误")
      },
      onResponseError(error) {
        // Status 是 HTTP 状态码
        const status = get(error, "response.status")
        switch (status) {
          case 400:
            error.message = "请求错误"
            break
          case 403:
            error.message = "拒绝访问"
            break
          case 404:
            error.message = "请求地址出错"
            break
          case 408:
            error.message = "请求超时"
            break
          case 500:
            error.message = "服务器内部错误"
            break
          case 501:
            error.message = "服务未实现"
            break
          case 502:
            error.message = "网关错误"
            break
          case 503:
            error.message = "服务不可用"
            break
          case 504:
            error.message = "网关超时"
            break
          case 505:
            error.message = "HTTP 版本不受支持"
            break
          default:
            break
        }
        ElMessage({ message: error.message, type: "error" })
        return Promise.reject(error)
      }
    }
  })
}

/** 创建请求方法 */
function createRequestFunction(service: AxiosInstance) {
  return function <T>(config: AxiosRequestConfig): Promise<T> {
    return service(config)
  }
}

/** 用于网络请求的实例 */
export const service = createService()
/** 用于网络请求的方法 */
export const request = createRequestFunction(service)
