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 }
    if (res && typeof res === "object" && "code" in res) {
      if (res.code !== 200 && res.code !== 0) {
        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 errorMessage =
      error.response?.data?.message || error.message || "网络错误"
    
    // 403 权限错误显示更友好的提示
    if (error.response?.status === 403) {
      message.error(errorMessage || "您没有权限执行此操作")
    } else {
      message.error(errorMessage)
    }

    if (error.response?.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
