import axios from 'axios'
import { toast } from 'react-hot-toast'
import { useGlobalStore } from '../context/useGlobalStore.js'
import { readToken } from '../context/authSession.js'

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

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

// Bind interceptors immediately so protected calls always include the token.
let isInterceptorBound = false

function bindInterceptorsOnce() {
  if (isInterceptorBound) return
  isInterceptorBound = true

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

    // global loading
    try {
      useGlobalStore.getState().showGlobalLoading()
    } catch {
      // ignore
    }

    return config
  })

  apiClient.interceptors.response.use(
    (response) => {
      try {
        useGlobalStore.getState().hideGlobalLoading()
      } catch {
        // ignore
      }
      return response
    },
    (error) => {
      try {
        useGlobalStore.getState().hideGlobalLoading()
      } catch {
        // ignore
      }

      const status = error?.response?.status
      const data = error?.response?.data
      const code = data?.error
      const message = data?.message || error.message

      toast.error(message || `Request failed${status ? ` (HTTP ${status})` : ''}`)

      return Promise.reject({ status, code, message })
    },
  )
}

bindInterceptorsOnce()

// Backwards compatibility if any code calls this function.
export function bindApiInterceptors() {
  bindInterceptorsOnce()
}


