/* ============================================================
   Carzello — document & photo storage (Cloudflare R2, bucket: carzello)
   Uploads flow through the app server (/api/storage/upload), which
   verifies the operator's Firebase token and holds the R2 key
   server-side. No storage secrets ship to the browser.
   ============================================================ */

const R2 = {
  /* upload(file, folder) → Promise<{ key, url }> — folders: photos | documents | claims */
  upload(file, folder = "misc") {
    const u = FB.enabled && FB.currentUser();
    if (!u) return Promise.reject(new Error("Sign in required."));
    const q = `folder=${encodeURIComponent(folder)}&name=${encodeURIComponent(file.name || "file")}`;
    return u.getIdToken()
      .then((tk) => fetch(`/api/storage/upload?${q}`, {
        method: "POST",
        headers: { "content-type": file.type || "application/octet-stream", authorization: "Bearer " + tk },
        body: file,
      }))
      .then((r) => {
        if (!r.ok) return r.json().then((e) => { throw new Error(e.error || `upload failed (${r.status})`); });
        return r.json();
      });
  },
};
