const baseUrl = (import.meta.env.VITE_API_BASE_URL || 'http://localhost:4001').replace(/\/$/, '')

async function request(path, { method = 'GET', body, token, headers = {} } = {}) {
  const url = `${baseUrl}${path}`
  const init = { method, headers: { ...headers } }

  if (token) {
    init.headers['x-admin-token'] = token
  }

  if (body !== undefined) {
    if (body instanceof FormData) {
      init.body = body
    } else {
      init.headers['Content-Type'] = init.headers['Content-Type'] || 'application/json'
      init.body = JSON.stringify(body)
    }
  }

  const response = await fetch(url, init)
  const text = await response.text()
  let data = null

  if (text) {
    try {
      data = JSON.parse(text)
    } catch (error) {
      data = text
    }
  }

  if (!response.ok) {
    const message = typeof data === 'object' && data !== null && 'error' in data
      ? data.error
      : `Request failed with status ${response.status}`
    const err = new Error(message)
    err.status = response.status
    err.data = data
    throw err
  }

  return data
}

export function getEvents() {
  return request('/api/events')
}

export function getEvent(slug) {
  return request(`/api/events/${slug}`)
}

export function createEvent(payload, token) {
  return request('/api/events', { method: 'POST', body: payload, token })
}

export function updateEvent(slug, payload, token) {
  return request(`/api/events/${slug}`, { method: 'PATCH', body: payload, token })
}

export function deleteEvent(slug, token) {
  return request(`/api/events/${slug}`, { method: 'DELETE', token })
}

export function verifyAdminToken(token) {
  return request('/api/admin/verify', { token })
}

export function uploadImage(file, token) {
  const form = new FormData()
  form.append('file', file)
  return request('/api/uploads', { method: 'POST', body: form, token })
}

export function getAdminToken() {
  return localStorage.getItem('annaville-admin-token') || ''
}

export function setAdminToken(token) {
  if (!token) {
    localStorage.removeItem('annaville-admin-token')
  } else {
    localStorage.setItem('annaville-admin-token', token)
  }
}
