import { getAuthToken } from './token'

const BASE_URL = '/api'

export async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {
  const method = options?.method?.toUpperCase() || 'GET'
  const headers: Record<string, string> = { ...options?.headers as Record<string, string> }

  // Auto-attach auth token
  const token = getAuthToken()
  if (token) {
    headers.Authorization = `Bearer ${token}`
  }

  if (['POST', 'PUT', 'PATCH'].includes(method) && options?.body) {
    headers['Content-Type'] = headers['Content-Type'] || 'application/json'
  }

  const res = await fetch(`${BASE_URL}${path}`, {
    ...options,
    headers,
    credentials: 'include',
  })
  if (!res.ok) {
    const errorData = await res.json().catch(() => ({}))
    throw new Error(errorData.message || `API Error: ${res.status}`)
  }
  return res.json()
}
