/* Firestore hooks — return [docs, ops] tuples so the rest of the app can
   stay close to the useState(seedX) shape it was originally written in.
   All paths are nested under /tenants/{tenantId}/. */

function useTenantCollection(name) {
  const fb = window.fb;
  const auth = window.useAuth();
  const tenantId = auth?.tenantId;
  const [docs, setDocs] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    if (!tenantId) { setDocs([]); setLoading(false); return; }
    setLoading(true);
    const col = fb.collection(fb.db, "tenants", tenantId, name);
    const unsub = fb.onSnapshot(col, (snap) => {
      const out = [];
      snap.forEach(d => out.push({ id: d.id, ...d.data() }));
      setDocs(out);
      setLoading(false);
    }, (err) => {
      console.error(`useTenantCollection(${name})`, err);
      setLoading(false);
    });
    return () => unsub();
  }, [tenantId, name]);

  const ops = React.useMemo(() => {
    if (!tenantId) return null;
    const col = () => fb.collection(fb.db, "tenants", tenantId, name);
    const d   = (id) => fb.doc(fb.db, "tenants", tenantId, name, id);
    return {
      // add(data) — autogenerate id, OR add({ id, ...data }) for explicit id
      add: async (data) => {
        const { id, ...rest } = data || {};
        if (id) { await fb.setDoc(d(id), rest); return id; }
        const ref = await fb.addDoc(col(), data);
        return ref.id;
      },
      // setMany: replace whole collection in batch (used by clearPlan)
      replaceAll: async (newDocs) => {
        const batch = fb.writeBatch(fb.db);
        const existing = await fb.getDocs(col());
        existing.forEach(snap => batch.delete(snap.ref));
        newDocs.forEach(({ id, ...rest }) => {
          const ref = id ? d(id) : fb.doc(col());
          batch.set(ref, rest);
        });
        await batch.commit();
      },
      update: (id, patch) => fb.updateDoc(d(id), patch),
      remove: (id) => fb.deleteDoc(d(id)),
      // setter shaped like React's setX(prev => prev.map/filter/...) so old call
      // sites in components-floor.jsx can keep their structure
      setter: (updater) => {
        const next = typeof updater === "function" ? updater(docs) : updater;
        return ops.replaceAll(next);
      },
    };
  }, [tenantId, name, docs]);

  return [docs, ops, loading];
}

// Seed a new tenant from window.SEATIQ_DATA. Used by admin create-restaurant.
async function seedTenant(tenantId) {
  const fb = window.fb;
  const data = window.SEATIQ_DATA;
  if (!data) return;
  const batch = fb.writeBatch(fb.db);
  const put = (col, id, payload) => {
    batch.set(fb.doc(fb.db, "tenants", tenantId, col, id), payload);
  };
  data.tables.forEach(t => put("tables", t.id, t));
  data.reservations.forEach(r => put("reservations", r.id, r));
  data.waitlist.forEach(w => put("waitlist", w.id, w));
  data.rooms.forEach(r => put("rooms", r.id, r));
  data.walls.forEach(w => put("walls", w.id, w));
  await batch.commit();
}

window.useTenantCollection = useTenantCollection;
window.seedTenant = seedTenant;
