/// <reference lib="dom" />
import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { test, WEB } from "./t3.ts";

test("The same label set reuses its fresh issue search", WEB, async ({t3,app,browser,screen}) => {
 const project = await t3.project("Issue label cache");
 execFileSync("git", ["remote","add","origin","https://github.com/pingdotgg/t3code.git"], {cwd:project});
 await t3.thread({project,title:"Label cache proof",messages:["Ready"]});
 await browser.addInitScript(() => {
  const searches: any[] = [];
  Object.assign(window,{issueSearches:searches});
  const send = WebSocket.prototype.send;
  WebSocket.prototype.send = function(data) {
   if(typeof data === "string") {
    const request = JSON.parse(data);
    if(request.tag === "issues.list") {
     searches.push(request.payload);
     const panel = document.getElementById("search-proof") ?? document.body.appendChild(Object.assign(document.createElement("pre"),{id:"search-proof"}));
     panel.style.cssText="position:fixed;bottom:12px;left:260px;z-index:99999;background:#111;color:#fff;padding:16px;font:14px monospace;max-width:850px";
     panel.textContent="Observed real issues.list requests (no interception)\n"+searches.map((x,i)=>`${i+1}. labels=${JSON.stringify(x.labels)}`).join("\n");
    }
   }
   return send.call(this,data);
  };
 });
 await t3.open("/issues");
 const select = async (label:string) => {
  await screen.getByRole("button", "Filters", {exact:false}).tap();
  await screen.getByRole("menuitem", "Labels", {exact:false}).tap();
  await screen.getByRole("menuitemcheckbox",label,{exact:true}).tap();
  await browser.evaluate(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:true})); return null;});
  await browser.locator('button[aria-label="Refresh issues"]:not(:disabled)').waitFor();
 };
 await select("documentation");
 await select("bug");

 await select("documentation");
 await select("documentation");
 await app.screenshot("same-labels-reselected");
 const count = await browser.evaluate(()=> (window as any).issueSearches.filter((x:any)=>x.labels?.length===2 && x.labels.includes("bug") && x.labels.includes("documentation")).length);
 expect(count).toBe(1);
});
