import { describe, expect, it } from "vitest";

import type { WorkbenchRealtimeEvent } from "@/api/workbench-events";
import { createWorkbenchReplayVisibilityRuntime } from "./workbench-replay-visibility";

describe("Workbench replay visibility", () => {
  it("keeps the visible projection stable until retained replay reaches live handoff", () => {
    const runtime = createWorkbenchReplayVisibilityRuntime();
    let visibleLastEventAt = "2026-07-21T12:00:00.000Z";
    const apply = (event: WorkbenchRealtimeEvent) => {
      visibleLastEventAt = String(event.event?.createdAt);
    };

    runtime.begin("session:ses_running");
    expect(runtime.stage("session:ses_running", kafkaFrame("2026-07-21T11:55:00.000Z"))).toBe(true);
    expect(runtime.stage("session:ses_running", kafkaFrame("2026-07-21T11:58:00.000Z"))).toBe(true);
    expect(runtime.stage("session:ses_running", kafkaFrame("2026-07-21T12:00:01.000Z"))).toBe(true);

    expect(visibleLastEventAt).toBe("2026-07-21T12:00:00.000Z");

    for (const frame of runtime.commit("session:ses_running")) apply(frame.event);
    expect(visibleLastEventAt).toBe("2026-07-21T12:00:01.000Z");

    expect(runtime.stage("session:ses_running", kafkaFrame("2026-07-21T12:00:03.000Z"))).toBe(false);
    apply(kafkaFrame("2026-07-21T12:00:03.000Z").event);
    expect(visibleLastEventAt).toBe("2026-07-21T12:00:03.000Z");
  });

  it("discards a partial replay when its stream is replaced", () => {
    const runtime = createWorkbenchReplayVisibilityRuntime();
    runtime.begin("session:ses_old");
    runtime.stage("session:ses_old", kafkaFrame("2026-07-21T11:55:00.000Z"));

    runtime.begin("session:ses_current");

    expect(runtime.commit("session:ses_old")).toEqual([]);
    expect(runtime.commit("session:ses_current")).toEqual([]);
  });

  it("does not delay non-business errors during replay", () => {
    const runtime = createWorkbenchReplayVisibilityRuntime();
    runtime.begin("session:ses_running");

    expect(runtime.stage("session:ses_running", {
      eventName: "workbench.error",
      event: { type: "error", error: "upstream unavailable" }
    })).toBe(false);
  });
});

function kafkaFrame(createdAt: string) {
  return {
    eventName: "hwlab.event.v1",
    event: {
      schema: "hwlab.event.v1",
      event: { traceId: "trc_replay", sessionId: "ses_running", createdAt }
    } as WorkbenchRealtimeEvent
  };
}
