const BASE_URL = '/api/registrations'

/**
 * 获取所有注册记录
 */
export async function getRegistrations() {
  const response = await fetch(BASE_URL)
  if (!response.ok) {
    throw new Error('获取注册列表失败')
  }
  return response.json()
}

/**
 * 根据ID获取单条注册记录
 * @param {number} id
 */
export async function getRegistrationById(id) {
  const response = await fetch(`${BASE_URL}/${id}`)
  if (response.status === 404) {
    return null
  }
  if (!response.ok) {
    throw new Error('获取注册记录失败')
  }
  return response.json()
}

/**
 * 创建注册记录
 * @param {object} registration
 */
export async function createRegistration(registration) {
  const response = await fetch(BASE_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(registration)
  })
  if (!response.ok) {
    throw new Error('创建注册记录失败')
  }
  return response.json()
}

/**
 * 更新注册记录
 * @param {number} id
 * @param {object} registration
 */
export async function updateRegistration(id, registration) {
  const response = await fetch(`${BASE_URL}/${id}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(registration)
  })
  return response.ok
}

/**
 * 删除注册记录
 * @param {number} id
 */
export async function deleteRegistration(id) {
  const response = await fetch(`${BASE_URL}/${id}`, {
    method: 'DELETE'
  })
  return response.ok
}