import axios, {
  InternalAxiosRequestConfig,
  type AxiosInstance,
  type AxiosResponse,
} from "axios"
import { message } from "ant-design-vue"
import { getToken, removeToken, getTenantCode } from "./auth"
import { useAuthStore } from "@/stores/auth"
import router from "@/router"

const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || "/api",
  timeout: 30000,
})

// Request interceptor
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = getToken()
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }

    // 添加租户信息到请求头
    // 租户编码从 URL 获取，租户ID 从用户信息获取
    const tenantCode = getTenantCode()
    const authStore = useAuthStore()
    const tenantId = authStore.user?.tenantId

    if (config.headers) {
      if (tenantCode) {
        config.headers["X-Tenant-Code"] = tenantCode
      }
      if (tenantId) {
        config.headers["X-Tenant-Id"] = String(tenantId)
      }
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// Response interceptor
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data

    // 如果响应已经是统一格式 { code, message, data }
    // 统一使用 code === 200 表示成功，不再兼容 code === 0
    if (res && typeof res === "object" && "code" in res) {
      if (res.code !== 200) {
        message.error(res.message || "请求失败")

        if (res.code === 401) {
          removeToken()
          // 从 URL 获取租户编码，跳转到对应的登录页
          const path = window.location.pathname
          const match = path.match(/^\/([^/]+)/)
          const tenantCode = match ? match[1] : null
          if (tenantCode && tenantCode !== "login") {
            router.push(`/${tenantCode}/login`)
          } else {
            router.push("/login")
          }
        }

        return Promise.reject(new Error(res.message || "请求失败"))
      }

      return res.data !== undefined ? res.data : res
    }

    // 如果响应是直接的数据，直接返回
    return res
  },
  (error) => {
    // 统一错误消息提取逻辑
    const serverMessage = error.response?.data?.message
    let errorMessage = "网络错误"

    if (serverMessage) {
      errorMessage = serverMessage
    } else if (error.code === "ECONNABORTED" || error.code === "ERR_CANCELED") {
      errorMessage = "请求超时，请稍后重试"
    } else if (!error.response) {
      errorMessage = "网络连接失败，请检查网络"
    }

    // 特殊状态码友好提示
    const status = error.response?.status
    if (status === 403) {
      errorMessage = "您没有权限执行此操作"
    } else if (status === 404) {
      errorMessage = "请求的资源不存在"
    } else if (status === 429) {
      errorMessage = "请求过于频繁，请稍后再试"
    } else if (status && status >= 500) {
      errorMessage = serverMessage || "服务器错误，请稍后重试"
    }

    message.error(errorMessage)

    if (status === 401) {
      removeToken()
      // 从 URL 获取租户编码，跳转到对应的登录页
      const path = window.location.pathname
      const match = path.match(/^\/([^/]+)/)
      const tenantCode = match ? match[1] : null
      if (tenantCode && tenantCode !== "login") {
        router.push(`/${tenantCode}/login`)
      } else {
        router.push("/login")
      }
    }

    return Promise.reject(error)
  }
)

export default service
