import axios, { type AxiosInstance, type AxiosError } from 'axios'
import { toast } from 'vue-sonner'
import { getBackendUrl } from '@/lib/backendUrl'

const apiClient: AxiosInstance = axios.create({
  baseURL: getBackendUrl() + '/api',
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 360000, // 6 minutes (LLM calls + SQL execution can be slow)
})

// Request interceptor
apiClient.interceptors.request.use(
  (config) => {
    // Add any auth headers here if needed
    return config
  },
  (error) => Promise.reject(error)
)

/**
 * Extract a user-friendly error message from an API error.
 */
function getErrorMessage(error: AxiosError): string {
  if (error.response) {
    const data = error.response.data as Record<string, unknown>
    // Backend returns { error: "message" }
    if (data?.error && typeof data.error === 'string') {
      return data.error
    }
    // Fallback to status text
    return `Error ${error.response.status}: ${error.response.statusText}`
  }
  if (error.request) {
    return 'Network error: No response from server'
  }
  return error.message || 'Unknown error'
}

// Response interceptor
apiClient.interceptors.response.use(
  (response) => response,
  (error: AxiosError) => {
    const message = getErrorMessage(error)

    // Log for debugging
    console.error('API Error:', message, error)

    // Show toast for server errors (5xx) and network errors
    // Client errors (4xx) are usually handled by components
    if (!error.response || error.response.status >= 500) {
      toast.error('Request failed', { description: message })
    }

    // Create a normalized error for components to catch
    const normalizedError = new Error(message)
    ;(normalizedError as any).status = error.response?.status
    ;(normalizedError as any).originalError = error

    return Promise.reject(normalizedError)
  }
)

export default apiClient
export { apiClient, getErrorMessage }
