import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Source control notices a terminal GitHub login when the window regains focus", WEB, async ({ t3, app, screen, browser }) => {
  const config = process.env.GH_CONFIG_DIR!;
  writeFileSync(join(config, "hosts.yml"), "");
  writeFileSync(join(config, "config.yml"), "");
  await t3.project("Source control demo");
  await t3.open("/settings/source-control");
  await screen.getByRole("button", "Toggle GitHub details").tap();
  await screen.getByText("Not authenticated", { exact: true }).first().waitFor({ state: "visible" });
  await browser.evaluate(() => {
    document.querySelector('[aria-label="Toggle GitHub details"]')?.scrollIntoView({ block: "center" });
  });
  await new Promise(resolve => setTimeout(resolve, 500));
  await app.screenshot("signed-out-github");
  const token = execFileSync("gh", ["auth", "token", "--hostname", "github.com"], {
    env: { ...process.env, GH_CONFIG_DIR: join(homedir(), ".config", "gh") }, encoding: "utf8",
  });
  execFileSync("gh", ["auth", "login", "--hostname", "github.com", "--with-token"], {
    env: { ...process.env, GH_CONFIG_DIR: config }, input: token, stdio: ["pipe", "pipe", "pipe"],
  });
  await new Promise(resolve => setTimeout(resolve, 35_000));
  await browser.evaluate(() => {
    window.dispatchEvent(new Event("focus"));
    document.dispatchEvent(new Event("visibilitychange"));
  });
  await new Promise(resolve => setTimeout(resolve, 5_000));
  await app.screenshot("after-terminal-login-and-return");
  await expect(screen.getByRole("button", "Reveal GitHub accounts")).toBeVisible();
});
