/**
 * API Request Wrapper
 * Handles secure pathing and basic response parsing
 */

export const request = async (url, options = {}) => {
  const settings = window.settings || {}
  const securePath = settings.secure_path || 'admin'
  
  // Format URL: prepend API path with secure path prefix
  let finalUrl = url
  if (!url.startsWith('http') && !url.startsWith('/api')) {
    finalUrl = `/api/v2/${securePath}/${url.replace(/^\//, '')}`
  }

  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
      // Auth headers will be handled by the browser session/cookies usually
      // but can be added here if needed.
    },
    ...options
  }

  try {
    const response = await fetch(finalUrl, defaultOptions)
    const data = await response.json()
    
    if (!response.ok) {
        throw new Error(data.message || 'Request failed')
    }
    
    return data
  } catch (error) {
    console.error(`API Error [${url}]:`, error)
    throw error
  }
}
