import axios, { AxiosError } from 'axios'
import { useAuthStore } from '@/stores/auth-store'

export const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '',
  timeout: 15000,
})

api.interceptors.request.use((config) => {
  const token = useAuthStore.getState().auth.accessToken
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

api.interceptors.response.use(
  (response) => response,
  (error: AxiosError) => {
    if (error.response?.status === 401) {
      useAuthStore.getState().auth.reset()
    }
    return Promise.reject(error)
  }
)

export function getApiErrorMessage(error: unknown, fallback = '请求失败') {
  if (error instanceof AxiosError) {
    const data = error.response?.data as
      | { message?: string | string[]; msg?: string; error?: string }
      | undefined
    const message = data?.msg || data?.message || data?.error
    if (Array.isArray(message)) {
      return message.join('，')
    }
    if (message) {
      return message
    }
  }

  if (error instanceof Error && error.message) {
    return error.message
  }

  return fallback
}

export type ApiEnvelope<T> = {
  code: number
  data: T | null
  msg: string
}

export function unwrapApiData<T>(payload: T | ApiEnvelope<T>): T {
  if (
    payload &&
    typeof payload === 'object' &&
    'code' in payload &&
    'data' in payload &&
    'msg' in payload
  ) {
    const envelope = payload as ApiEnvelope<T>
    if (envelope.code !== 0) {
      throw new Error(envelope.msg || '请求失败')
    }
    return envelope.data as T
  }

  return payload as T
}
