import { buildApiUrl, toUserFacingApiError } from './apiBase'

function buildHeaders(token, hasBody) {
  return {
    ...(hasBody ? { 'Content-Type': 'application/json' } : {}),
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  }
}

async function request(path, { method = 'GET', token, body } = {}) {
  const hasBody = body !== undefined
  const response = await fetch(buildApiUrl(path), {
    method,
    headers: buildHeaders(token, hasBody),
    body: hasBody ? JSON.stringify(body) : undefined,
  })

  const data = await response.json().catch(() => ({}))

  if (!response.ok) {
    throw new Error(toUserFacingApiError(data, '플래너 데이터를 처리하지 못했습니다.'))
  }

  return data
}

export async function fetchPlannerEntries(token, range = {}) {
  const searchParams = new URLSearchParams()

  if (range.from) {
    searchParams.set('from', range.from)
  }

  if (range.to) {
    searchParams.set('to', range.to)
  }

  const query = searchParams.toString()
  return request(`/api/planner${query ? `?${query}` : ''}`, {
    token,
  })
}

export async function savePlannerEntry(token, entryDate, payload) {
  return request(`/api/planner/${entryDate}`, {
    method: 'PUT',
    token,
    body: {
      payload,
    },
  })
}

export async function deletePlannerEntry(token, entryDate) {
  return request(`/api/planner/${entryDate}`, {
    method: 'DELETE',
    token,
  })
}
