import axios, { type AxiosInstance, type AxiosResponse, type AxiosError } from 'axios'

const STATUS_CODE_SUCCESS = 200

export const API_URL = import.meta.env.VITE_APP_API || ''

// Create axios instance
const instance: AxiosInstance = axios.create({
  baseURL: API_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: false,
})

// Request interceptor
instance.interceptors.request.use(
  config => {
    // Add request interceptors here (e.g., auth tokens)
    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

// Response interceptor
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response?.status !== STATUS_CODE_SUCCESS) {
      return Promise.reject(response?.data)
    }
    return response.data
  },
  (error: AxiosError) => {
    if (error?.response?.data) {
      return Promise.reject(error?.response?.data)
    }
    return Promise.reject(error)
  }
)

// Set locale for API requests
export const setLocaleApi = (locale: string) => {
  instance.defaults.headers.common['lang'] = locale
}

export default instance

