import axios from 'axios'

// Axios 인스턴스 생성
const createApiClient = () => {
  const config = useRuntimeConfig()
  const apiBase = config.public.apiBase || 'http://localhost'
  
  const client = axios.create({
    baseURL: apiBase,
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json',
      'X-Requested-With': 'XMLHttpRequest'
    }
  })

  // 요청 인터셉터
  client.interceptors.request.use(
    (config) => {
      //console.log('API Request:', config.method?.toUpperCase(), config.url)
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  // 응답 인터셉터
  client.interceptors.response.use(
    (response) => {
      return response
    },
    (error) => {
      console.error('API Error:', error.response?.status, error.response?.data)
      return Promise.reject(error)
    }
  )

  return client
}

// API 클라이언트 싱글톤
let apiClient = null

const getApiClient = () => {
  if (!apiClient) {
    apiClient = createApiClient()
  }
  return apiClient
}

// 글로벌 API 메서드들 (직접 사용 가능)
export const $get = async (url, params = {}) => {
  try {
    const client = getApiClient()
    const response = await client.get(url, { params })
    return response.data
  } catch (error) {
    throw error
  }
}

export const $post = async (url, data = {}) => {
  try {
    const client = getApiClient()
    const response = await client.post(url, data)
    return response.data
  } catch (error) {
    throw error
  }
}

export const $postForm = async (url, data = {}) => {
  try {
    const client = getApiClient()
    const formData = new FormData()
    Object.keys(data).forEach(key => {
      formData.append(key, data[key])
    })

    const response = await client.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response.data
  } catch (error) {
    throw error
  }
}

export const put = async (url, data = {}) => {
  try {
    const client = getApiClient()
    const response = await client.put(url, data)
    return response.data
  } catch (error) {
    throw error
  }
}

export const del = async (url, params = {}) => {
  try {
    const client = getApiClient()
    const response = await client.delete(url, { params })
    return response.data
  } catch (error) {
    throw error
  }
}

// Nuxt 4 composables를 위한 기본 export
export default () => ({
  get,
  post,
  postForm,
  put,
  delete: del
})

// 기존 useApi 호환성을 위해 유지
export const useApi = () => ({
  get,
  post,
  postForm,
  put,
  delete: del
})