/// <reference lib="dom" />
import { ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("A stale guest history failure preserves the newer pending load", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("guest-history-demo");
  const thread = await t3.thread({project, title: "Guest history ownership", messages: Array.from({length:31}, (_,i)=>`turn ${i+1}`)});
  const {cli} = makeState(T3_HOME, process.env);
  try {
    const share = await runPromise(Effect.gen(function*(){
      const client = yield* rpcClient(T3_HOME, app.baseUrl);
      return yield* client["guestShare.create"]({threadId: ThreadId.make(thread.threadId)}).pipe(
        Effect.retry({schedule:Schedule.spaced("1 second"), times:90})
      );
    }).pipe(Effect.scoped));
    await browser.addInitScript(() => {
      const nativeFetch = window.fetch.bind(window);
      const requests: Array<{cursor:string; reject:(reason:unknown)=>void; release:()=>void}> = [];
      Object.assign(window, {historyRequests: requests});
      window.fetch = (input, init) => {
        const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, location.href);
        if (url.pathname !== "/api/guest/history") return nativeFetch(input, init);
        return new Promise<Response>((resolve,reject)=> {
          requests.push({cursor:url.searchParams.get("cursor") ?? "", reject, release:()=>{void nativeFetch(input,init).then(resolve,reject);}});
        });
      };
      let saw32=false;
      let resolve32:()=>void;
      const live32=new Promise<void>(r=>{resolve32=r;});
      Object.assign(window,{waitForLive32:()=>saw32?Promise.resolve():live32});
      const Native = window.EventSource;
      class ControlledSource extends EventTarget {
        static CONNECTING=0; static OPEN=1; static CLOSED=2;
        source: EventSource;
        constructor(readonly url:string|URL, readonly options?:EventSourceInit) {
          super(); this.source=this.connect();
          Object.assign(window,{reconnectGuest:()=>{this.source.close(); this.source=this.connect();}});
        }
        connect() {
          const source=new Native(this.url,this.options);
          for(const type of ["message","open","error"]) source.addEventListener(type,(event)=> {
            if(type === "message" && (event as MessageEvent).data.includes('turn 32')) {saw32=true;resolve32();}
            this.dispatchEvent(type === "message" ? new MessageEvent(type,{data:(event as MessageEvent).data}) : new Event(type));
          });
          return source;
        }
        get readyState(){return this.source.readyState;}
        close(){this.source.close();}
      }
      Object.assign(window,{EventSource:ControlledSource});
    });
    await browser.goto(share.url);
    await screen.getByRole("textbox", "Your name").fill("Repro guest");
    await screen.getByRole("button", "Join", {exact:true}).click();
    await screen.getByText("turn 31", {exact:true}).waitFor({timeout:60_000});
    const earlier=screen.getByRole("button", /earlier turns/);
    await earlier.click();
    await screen.getByText("Loading earlier turns…", {exact:true}).waitFor();
    await runPromise(cli(["thread","send",thread.threadId,"turn 32","--wait","--json"]));
    await browser.evaluate("window.waitForLive32().then(()=>null)");
    await browser.evaluate("window.reconnectGuest()");
    await screen.getByText("Loading earlier turns…",{exact:true}).waitFor({state:"hidden",timeout:60_000});
    await earlier.click();
    await screen.getByText("Loading earlier turns…",{exact:true}).waitFor();
    const cursors=await browser.evaluate("window.historyRequests.map(r=>r.cursor)");
    if(!Array.isArray(cursors)||cursors.length!==2||cursors[0]===cursors[1]) throw new Error("The real reconnect did not establish two distinct history cursors");
    await app.screenshot("newer-history-request-pending");
    await browser.evaluate("window.historyRequests[0].reject(new TypeError('Failed to fetch'))");
    await browser.evaluate(async()=>{await new Promise<void>(r=>requestAnimationFrame(()=>requestAnimationFrame(()=>r())));return null;});
    try {
      await expect(earlier).toBeDisabled();
    } finally {
      await app.screenshot("stale-failure-while-newer-request-pending");
    }
    await browser.evaluate("window.historyRequests[1].release()");
    await screen.getByText("turn 1",{exact:true}).waitFor({timeout:60_000});
    await app.screenshot("earlier-history-loaded");
  } finally {
    await runPromise(cli(["connect","logout"]));
  }
});
