import axios from 'axios'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000'

const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
})

const getToken = () => {
  try {
    return localStorage.getItem('sms_token')
  } catch {
    return null
  }
}

api.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => Promise.reject(error),
)

api.interceptors.response.use(
  (response) => response,
  (error) => {
    const status = error?.response?.status

    if (status === 401 || status === 403) {
      // Avoid importing auth context here to prevent circular dependencies.
      try {
        localStorage.removeItem('sms_token')
        localStorage.removeItem('sms_user')
      } catch {
        // ignore
      }
      // Let UI handle redirects on next navigation.
    }

    const message =
      error?.response?.data?.message ||
      error?.response?.data?.error ||
      error?.message ||
      'Request failed'

    return Promise.reject(new Error(message))
  },
)

export { API_BASE_URL }
export default api

