const DB = (() => {
  async function req(path, method = "GET", body) {
    const res = await fetch("/api" + path, {
      method,
      headers: body !== undefined ? { "Content-Type": "application/json" } : {},
      body: body !== undefined ? JSON.stringify(body) : undefined,
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data?.error || res.statusText);
    return data;
  }

  const loadRooms     = ()           => req("/rooms");
  const addRoom       = (room)       => req("/rooms", "POST", room);
  const deleteRoom    = (no)         => req(`/rooms/${encodeURIComponent(no)}`, "DELETE");
  const updateRoom    = (no, patch)  => req(`/rooms/${encodeURIComponent(no)}`, "PATCH", patch);
  const checkIn       = (no, cust)   => req(`/checkin/${encodeURIComponent(no)}`, "POST", cust);
  const loadSettings  = ()           => req("/settings");
  const saveSetting   = (key, val)   => req(`/settings/${encodeURIComponent(key)}`, "PUT", val);

  const loadParking   = ()           => req("/parking");
  const addSpot       = (spot)       => req("/parking", "POST", spot);
  const deleteSpot    = (no)         => req(`/parking/${encodeURIComponent(no)}`, "DELETE");
  const updateSpot    = (no, patch)  => req(`/parking/${encodeURIComponent(no)}`, "PATCH", patch);

  return { loadRooms, addRoom, deleteRoom, updateRoom, checkIn, loadSettings, saveSetting,
           loadParking, addSpot, deleteSpot, updateSpot };
})();

window.DB = DB;
