import { connectEventSource, createEventSyncController } from "../../../apps/web/src/event-sync.js";

interface TimelineEntry {
  action: string;
  detail?: string;
}

declare global {
  interface Window {
    wp0EventFixture: {
      timeline: TimelineEntry[];
    };
  }
}

const timeline: TimelineEntry[] = [];
const request = async (url: string, action: string, detail?: string) => {
  timeline.push({ action, ...(detail ? { detail } : {}) });
  const response = await fetch(url);
  if (!response.ok) throw new Error(`${action} failed`);
  await response.json();
};

const controller = createEventSyncController({
  bootstrap: () => request("/api/v1/bootstrap", "bootstrap"),
  refetchEntity: (entityRef) =>
    request(`/__test/entity?ref=${encodeURIComponent(entityRef)}`, "refetch_entity", entityRef),
  refetchModels: (input) =>
    request("/__test/models", "refetch_models", input.reason),
});
const source = connectEventSource("/api/v1/events", controller);
source.addEventListener("open", () => {
  timeline.push({ action: "connected" });
  document.getElementById("status")!.textContent = "connected";
});

window.wp0EventFixture = { timeline };
