// Core API Client sử dụng Native Fetch
const BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000'

/**
 * Hàm gọi API chung tự động gắn Header và xử lý lỗi
 */
export async function apiClient(endpoint, { method = 'GET', data = null, headers = {}, customUrl = null } = {}) {
  const url = customUrl ? \`\${customUrl}\${endpoint}\` : \`\${BASE_URL}\${endpoint}\`
  
  const config = {
    method,
    headers: {
      'Content-Type': 'application/json',
      // 'Authorization': \`Bearer \${localStorage.getItem('token')}\` // Toggle if using tokens
      ...headers
    }
  }

  if (data) {
    config.body = JSON.stringify(data)
  }

  try {
    const response = await fetch(url, config)

    // Xử lý unauthenticated
    if (response.status === 401) {
      window.location.href = '/sign-in'
      throw new Error('Unauthorized - Redirecting to login')
    }

    const json = await response.json()
    
    if (!response.ok) {
      throw new Error(json.message || 'API request failed')
    }

    return json
  } catch (error) {
    console.error('[API Error]:', error)
    throw error
  }
}
