import { expect } from "e2e";
import { writeFile, chmod, unlink, readFile } from "node:fs/promises";
import { join } from "node:path";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("A stalled GitCafe credential helper explains the timeout and Retry recovers", { ...WEB, timeout: 900_000 },
  async ({ t3, app, browser, screen }) => {
    const flag = join(T3_HOME, "stall-credential");
    const calls = join(T3_HOME, "credential-calls");
    const shim = join(T3_HOME, "bin", "cafe");
    await writeFile(shim, `#!/bin/sh
printf '%s\\n' "$*" >> "$(dirname "$0")/../cafe-calls"
case "$*" in
  "auth http credential --host https://git.cafe/api get")
    echo credential >> "$(dirname "$0")/../credential-calls"
    if [ -f "$(dirname "$0")/../stall-credential" ]; then exec sleep 60; fi
    printf 'protocol=https\nhost=git.cafe\nusername=token\npassword=%s\n\n' "$PROOF_CAFE_TOKEN"
    exit 0 ;;
esac
CAFE_TOKEN="$PROOF_CAFE_TOKEN" exec "$PROOF_REAL_CAFE" "$@"
`);
    await chmod(shim, 0o755);
    await browser.emulateMedia({ colorScheme: "dark" });
    await t3.project("Credential timeout demo", {
      ".git/config": '[remote "origin"]\n  url = https://git.cafe/pingdotgg/t3code.git\n  fetch = +refs/heads/*:refs/remotes/origin/*\n',
    });
    await t3.open("/pull-requests?host=git.cafe");
    const refresh = screen.getByRole("button", "Refresh pull requests", { exact: true });
    await refresh.waitFor({ timeout: 60_000 });
    // Let the initial request finish, then expire the real five-minute credential cache.
    await browser.locator('[data-pull-request-key]').first().waitFor({ timeout: 60_000 });
    await app.screenshot("loaded-pull-requests");
    await writeFile(flag, "stall");
    await new Promise(resolve => setTimeout(resolve, 301_000));
    await refresh.tap();
    const failure = screen.getByText(/Pull request operation list failed:/).first();
    await failure.waitFor({ timeout: 60_000 });
    await browser.locator('button[aria-label="Refresh pull requests"]:not(:disabled)').waitFor({ timeout: 60_000 });
    await failure.scrollIntoView();
    await app.screenshot("credential-timeout");
    const timeoutExplained = await screen.getByText(/within 10 seconds.*try again/).first().isVisible();
    const misleadingAdvice = await screen.getByText(/Check.*cafe auth status/).first().isVisible();
    const beforeRetry = (await readFile(calls, "utf8")).trim().split("\n").length;
    await unlink(flag);
    await screen.getByRole("button", "Retry", { exact: true }).tap();
    await failure.waitFor({ state: "hidden", timeout: 60_000 });
    await app.screenshot("retry-recovers");
    const afterRetry = (await readFile(calls, "utf8")).trim().split("\n").length;
    expect(afterRetry > beforeRetry, "Retry calls the credential helper again").toBe(true);
    expect(timeoutExplained && !misleadingAdvice, "The banner explains the 10-second timeout and suggests retrying, without sign-in advice").toBe(true);
  });
