import { filterPersistableAutosaveUpdates } from '../services/project-context.js';
import { autosaveState, state } from '../state/app-state.js';

export function flushAutosaveWithBeacon() {
  if (!state.batch || !autosaveState.pendingByEntity.size || !navigator.sendBeacon) return;
  const endpoint = `/api/batch/${encodeURIComponent(state.batch)}/save`;
  const entries = Array.from(autosaveState.pendingByEntity.entries());
  entries.forEach(([, payload]) => {
    const updates = filterPersistableAutosaveUpdates(payload.entity, payload.updates);
    if (!Object.keys(updates).length) return;
    const body = { updates };
    if (payload.entity.recordId != null) {
      body.record_id = payload.entity.recordId;
    } else if (payload.entity.headerId != null) {
      body.header_id = payload.entity.headerId;
    } else {
      return;
    }
    const sent = navigator.sendBeacon(endpoint, new Blob([JSON.stringify(body)], { type: "application/json" }));
    if (sent) {
      const entityKey = payload.entity.recordId != null
        ? `record:${payload.entity.recordId}`
        : `header:${payload.entity.headerId}`;
      autosaveState.pendingByEntity.delete(entityKey);
    }
  });
}


export async function api(path, opts) {
  const r = await fetch(path, {
    credentials: "same-origin",
    headers: { "Content-Type": "application/json", Accept: "application/json" },
    ...opts,
  });
  const text = await r.text();
  if (!r.ok) {
    let msg = text;
    try {
      const j = JSON.parse(text);
      if (j.error) msg = j.error;
    } catch (_) {
      const pMatch = text.match(/<p>([\s\S]*?)<\/p>/i);
      if (pMatch && pMatch[1]) {
        msg = pMatch[1].replace(/<[^>]*>/g, "").trim();
      }
    }
    throw new Error(msg || r.statusText);
  }
  if (r.status === 204) return null;
  return text ? JSON.parse(text) : null;
}
