import { STATUS_CODE_SUCCESS } from '@/utils/constants/code'
import axios from 'axios'

axios.defaults.withCredentials = false

export const API_URL = import.meta.env.VITE_APP_API
const instance = axios.create({
    baseURL: API_URL,
    headers: {
        'Content-Type': 'application/json',
    },
})

instance.interceptors.response.use(
    (response) => {
        return response
    },
    (error) => {
        return Promise.reject(error)
    }
)

instance.interceptors.response.use(
    function (response) {
        if (response?.status !== STATUS_CODE_SUCCESS) return Promise.reject(response?.data)
        return response.data
    },
    function (error) {
        if (error?.response?.data) {
            return Promise.reject(error?.response?.data)
        }
        return Promise.reject(error)
    }
)

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

export default instance
