import axios from 'axios'
import {
  readAccessToken,
  refreshAccessToken,
  notifyUnauthenticated,
} from '../auth/token-bridge'

export const apiClient = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  withCredentials: true, // send httpOnly cc_refresh_token cookie on refresh calls
})

apiClient.interceptors.request.use((config) => {
  const token = readAccessToken()
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
})

apiClient.interceptors.response.use(
  (res) => res,
  async (err) => {
    const original = err.config
    const status = err.response?.status
    const url = original?.url || ''

    // Never try to refresh on the refresh endpoint itself — that's a terminal failure.
    const isRefreshCall = url.includes('/internal/auth/refresh')

    if (status === 401 && original && !original._retry && !isRefreshCall) {
      original._retry = true
      const newToken = await refreshAccessToken()
      if (newToken) {
        original.headers.Authorization = `Bearer ${newToken}`
        return apiClient(original)
      }
      notifyUnauthenticated()
    }
    return Promise.reject(err)
  },
)
