/** API calls specific to FCM token registration and reminder settings. */

const BASE = import.meta.env.VITE_API_URL || 'http://localhost:8001/api'

async function post(url: string, body: unknown, token: string) {
  const res = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
    credentials: 'include',
    body: JSON.stringify(body),
  })
  if (!res.ok) {
    const err = await res.json().catch(() => ({}))
    throw new Error(err.detail || res.statusText)
  }
  return res.json()
}

async function put(url: string, body: unknown, token: string) {
  const res = await fetch(url, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
    credentials: 'include',
    body: JSON.stringify(body),
  })
  if (!res.ok) {
    const err = await res.json().catch(() => ({}))
    throw new Error(err.detail || res.statusText)
  }
  return res.json()
}

export function saveFcmToken(userId: string, fcmToken: string, authToken: string) {
  return post(`${BASE}/notifications/fcm-token`, { userId, fcmToken }, authToken)
}

export function saveReminderSettings(
  userId: string,
  settings: { time?: string; enabled: boolean; timezone?: string },
  authToken: string
) {
  return put(`${BASE}/notifications/reminder/${userId}`, settings, authToken)
}
