import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const prId = "PR_kwDORLtfbc8AAAABPfqKDg";
const file = "apps/mobile/src/features/pull-requests/pullRequestDiffDebug.ts";
function github(query: string) {
  return JSON.parse(execFileSync("/usr/bin/gh", ["api", "graphql", "-f", `query=${query}`], { encoding: "utf8" }));
}
function viewed(value: boolean) {
  github(`mutation { ${value ? "markFileAsViewed" : "unmarkFileAsViewed"}(input:{pullRequestId:"${prId}",path:"${file}"}) { clientMutationId } }`);
}

test("Clearing Viewed on GitHub unfolds the file after an in-place refresh", WEB, async ({t3, app, screen, browser}) => {
  const initial = github(`query { node(id:"${prId}") { ... on PullRequest { files(first:100) { nodes { path viewerViewedState } } } } }`).data.node.files.nodes.find((f: {path:string}) => f.path === file).viewerViewedState;
  try {
    viewed(false);
    const project = await t3.project("Viewed files example");
    execFileSync("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], {cwd:project});
    const thread = await t3.thread({project, title:"Review Viewed files", messages:["Prepare this review"]});
    await t3.open(thread);
    await app.open("/settings/diffs");
    await screen.getByRole("combobox", "Default diff file state").tap();
    await screen.getByRole("option", "Expanded").tap();
    await app.open('/pull-requests?repository=pingdotgg%2Ft3code&number=37605&selectedUrl=https%3A%2F%2Fgithub.com%2Fpingdotgg%2Ft3code%2Fpull%2F37605');
    await screen.getByRole("button", "Code").tap();
    await screen.getByRole("checkbox", "Viewed").first().tap();
    // Wait for the app's debounced write to reach GitHub before changing the same mark there.
    for (let i=0;i<40;i++) {
      const state = github(`query { node(id:"${prId}") { ... on PullRequest { files(first:100) { nodes { path viewerViewedState } } } } }`).data.node.files.nodes.find((f: {path:string}) => f.path === file).viewerViewedState;
      if (state === "VIEWED") break;
      await new Promise(resolve => setTimeout(resolve,500));
      if (i===39) throw new Error("Viewed write did not reach GitHub");
    }
    await app.screenshot("marked-viewed");
    viewed(false);
    await screen.getByRole("button", "Refresh pull requests").tap();
    await expect(screen.getByRole("checkbox", "Viewed").first()).not.toBeChecked();
    await app.screenshot("cleared-on-github-and-refreshed");
    await expect(browser.locator('[slot="header-prefix"] button').first()).toHaveAttribute("aria-expanded", "true");
  } finally {
    viewed(initial === "VIEWED");
  }
});
