import { apiBase } from './config'
import { useAuthStore } from '../store/authStore'

function authHeaders() {
  const token = useAuthStore.getState().token
  return {
    'Content-Type': 'application/json',
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  }
}

export async function fetchBookings() {
  const res = await fetch(`${apiBase}/api/bookings`, {
    method: 'GET',
    headers: authHeaders(),
  })
  if (!res.ok) {
    throw new Error(`Failed to load bookings (${res.status})`)
  }
  return res.json()
}

export async function createBooking(payload) {
  const res = await fetch(`${apiBase}/api/bookings`, {
    method: 'POST',
    headers: authHeaders(),
    body: JSON.stringify(payload),
  })
  if (!res.ok) {
    const text = await res.text().catch(() => '')
    throw new Error(text || `Failed to save booking (${res.status})`)
  }
  return res.json().catch(() => ({}))
}
