import Axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios'
import keycloak from './keycloak'

const http = Axios.create({
  timeout: 1000000000, // เพิ่มค่า timeout
  headers: {
    'X-Requested-With': 'XMLHttpRequest'
  }
})

http.interceptors.request.use(
  async function (config: AxiosRequestConfig<any>) {
    await keycloak.updateToken(1)
    config.headers = config.headers ?? {}
    const token = keycloak.token
    if (token) config.headers.Authorization = `Bearer ${token}`
    return config
  },
  function (error: any) {
    return Promise.reject(error)
  }
)

http.interceptors.response.use(
  function (response: AxiosResponse<any, any>) {
    return response
  },
  function (error: any) {
    if (typeof error !== undefined) {
      // eslint-disable-next-line no-prototype-builtins
      if (error.hasOwnProperty('response')) {
        if (error.response.status === 401 || error.response.status === 403) {
          // Store.commit("SET_ERROR_MESSAGE", error.response.data.message);
          // Store.commit("REMOVE_ACCESS_TOKEN")
        }
      }
    }
    return Promise.reject(error)
  }
)

export default http
