import axios, { AxiosHeaders } from 'axios'
import { apiBaseURL } from '@/shared/config'

export const apiClient = axios.create({
  baseURL: apiBaseURL,
})

apiClient.interceptors.request.use((config) => {
  try {
    config.headers = AxiosHeaders.from(config.headers ?? {})
    const token = localStorage.getItem('craftshop_auth_token')
    if (token) {
      config.headers.set('Authorization', `Bearer ${token}`)
    }
    if (config.data instanceof FormData) {
      config.headers.delete('Content-Type')
      config.headers.delete('content-type')
    }
    return config
  } catch {
    return config
  }
})

apiClient.interceptors.response.use(undefined, (error) => {
  const ct = error.response?.headers?.['content-type'] ?? ''
  if (error.response?.status === 403 && ct.includes('text/html')) {
    document.open()
    document.write(error.response.data)
    document.close()
  }
  return Promise.reject(error)
})
