import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { mkdir, writeFile } from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Workflow stop and Git pull follow the selected language", WEB, async ({t3, app, screen}) => {
  const project = await t3.project("Translation demo");
  const git = (...args: string[]) => execFileSync("git", args, {cwd: project});
  git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", "Upstream update");
  git("clone", "--bare", project, `${project}-remote.git`);
  git("reset", "--hard", "HEAD~1");
  git("remote", "add", "origin", `${project}-remote.git`);
  git("fetch", "origin", "main:refs/remotes/origin/main");
  git("branch", "--set-upstream-to=origin/main", "main");
  const thread = await t3.thread({project, title: "Translation check", messages: ["Start"]});
  await mkdir(`${T3_HOME}/workflows`, {recursive:true});
  await writeFile(`${T3_HOME}/workflows/translation.ts`, `T3.workflow("translation-check", {version:1, payload:Schema.Struct({})}, () => T3.ask("confirm", {title:"Continue the demonstration?", choices:["Continue","Hold"]}));`);
  await t3.open("/settings/labs");
  await screen.getByLabel("Workflows", {exact:true}).tap();
  await runPromise(makeState(T3_HOME).cli(["workflow", "start", "translation-check", "--input", "{}", "--key", "translation-proof"]));
  await t3.open("/settings/general");
  await screen.getByLabel("Language", {exact:true}).tap();
  await screen.getByText("Português (Brasil)", {exact:true}).tap();
  await t3.open(thread);
  await screen.getByRole("button", /^(Pull|Fazer pull)$/).waitFor();
  await app.screenshot("portuguese-git-pull");
  await expect.soft(screen.getByRole("button", /^(Pull|Fazer pull)$/)).toHaveText("Fazer pull");
  await t3.open("/workflows");
  await screen.getByText("Continue the demonstration?", {exact:true}).first().tap();
  const stop = screen.getByRole("button", /^(Stop|Parar)$/);
  await stop.waitFor();
  await app.screenshot("portuguese-workflow-stop");
  await expect.soft(stop).toHaveText("Parar");
  await t3.open("/settings/general");
  await screen.getByLabel("Idioma", {exact:true}).tap();
  await screen.getByText("Deutsch", {exact:true}).tap();
  await t3.open("/workflows");
  await screen.getByText("Continue the demonstration?", {exact:true}).first().tap();
  const germanStop = screen.getByRole("button", /^(Stop|Stoppen)$/);
  await germanStop.waitFor();
  await app.screenshot("german-workflow-stop");
  await expect(germanStop).toHaveText("Stoppen");
});
