import axios, { AxiosError, type AxiosRequestConfig } from 'axios'
import { message } from 'antd'
import type { ApiResponse } from '@/types/system'
import { storage } from './storage'

const instance = axios.create({
  baseURL: import.meta.env.VITE_BASE_API || '/api',
  timeout: 60000,
})

instance.interceptors.request.use((config) => {
  const token = storage.getToken()
  if (token) {
    config.headers['x-token'] = token
  }

  return config
})

instance.interceptors.response.use(
  (response) => response,
  (error: AxiosError<ApiResponse<unknown>>) => {
    const status = error.response?.status
    const errorText = error.response?.data?.msg || error.message || '请求失败'

    if (status === 401) {
      storage.clearToken()
      window.location.hash = '#/login'
      window.location.reload()
      return Promise.reject(error)
    }

    message.error(errorText)
    return Promise.reject(error)
  },
)

async function request<T>(config: AxiosRequestConfig) {
  const response = await instance.request<ApiResponse<T>>(config)
  const payload = response.data

  if (typeof payload?.code === 'number' && payload.code !== 0) {
    message.error(payload.msg || '请求失败')
    throw new Error(payload.msg || '请求失败')
  }

  return payload
}

export const http = {
  get<T>(url: string, config?: AxiosRequestConfig) {
    return request<T>({ ...config, url, method: 'get' })
  },
  post<T>(url: string, data?: unknown, config?: AxiosRequestConfig) {
    return request<T>({ ...config, url, data, method: 'post' })
  },
  put<T>(url: string, data?: unknown, config?: AxiosRequestConfig) {
    return request<T>({ ...config, url, data, method: 'put' })
  },
  delete<T>(url: string, config?: AxiosRequestConfig) {
    return request<T>({ ...config, url, method: 'delete' })
  },
}
