import axios from 'axios'
import { logger } from '../utils/logger'

// Use VITE_API_URL if set, fallback to /api for local development proxy
const apiBaseUrl = import.meta.env.VITE_API_URL || '/api'
logger.info('🔗 [apiClient] Using API base URL:', apiBaseUrl)

const instance = axios.create({
  baseURL: apiBaseUrl,
  timeout: 8000
})

let token: string | null = null

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

instance.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      logger.warn('Sessão expirada, por favor, faça login novamente.')
    }
    return Promise.reject(error)
  }
)

export const apiClient = {
  get: <T>(url: string) => instance.get<T>(url).then(r => r.data),
  post: <T>(url: string, data?: unknown) => instance.post<T>(url, data).then(r => r.data),
  put: <T>(url: string, data?: unknown) => instance.put<T>(url, data).then(r => r.data),
  patch: <T>(url: string, data?: unknown) => instance.patch<T>(url, data).then(r => r.data),
  delete: (url: string) => instance.delete(url).then(r => r.data),
  setToken: (value: string | null) => {
    token = value
  }
}
