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 fetchGoals(token, { query = '', status = 'active' } = {}) {
  const searchParams = new URLSearchParams()

  if (query) {
    searchParams.set('query', query)
  }

  if (status) {
    searchParams.set('status', status)
  }

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

export async function createGoal(token, payload) {
  return request('/api/goals', {
    method: 'POST',
    token,
    body: payload,
  })
}

export async function updateGoal(token, goalId, payload) {
  return request(`/api/goals/${goalId}`, {
    method: 'PATCH',
    token,
    body: payload,
  })
}

export async function deleteGoal(token, goalId) {
  return request(`/api/goals/${goalId}`, {
    method: 'DELETE',
    token,
  })
}
