import axios from 'axios'

// Get runtime config for Nuxt 3
const config = useRuntimeConfig()

// Create axios instance for local API
const api = axios.create({
  baseURL: config.public.baseUrl,
  timeout: 10000,
})

// Create axios instance for GoMed API
const apiGomed = axios.create({
  baseURL: config.public.baseUrlGomed,
  timeout: 10000,
})

// Shared request interceptor
const requestInterceptor = (config: any) => {
  const token = localStorage.getItem('token')

  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }

  return config
}

// Shared response interceptor
const responseInterceptor = (response: any) => response
const responseErrorInterceptor = (error: any) => {
  // centralized error
  console.error('API Error:', error.response)
  return Promise.reject(error)
}

// Apply interceptors to both instances
api.interceptors.request.use(requestInterceptor)
api.interceptors.response.use(responseInterceptor, responseErrorInterceptor)

apiGomed.interceptors.request.use(requestInterceptor)
apiGomed.interceptors.response.use(responseInterceptor, responseErrorInterceptor)

export default api
export { apiGomed }