import { expect } from "e2e";
import { test, WEB } from "./t3.ts";
import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { join } from "node:path";
const sh = (program: string, args: string[], cwd?: string) => execFileSync(program, args, {cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"]}).trim();
const template = "## Template Context\n\nDescribe the change.\n\n## Template Verification\n\nDescribe verification.\n";
const helper = '!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f';

test("Azure PR descriptions follow default branch template", WEB, async ({t3, app, screen, browser}) => {
  await browser.setViewport({width:1440,height:900});
  const fixtures = [];
  for (const target of ["main", "release"]) {
    const project = await t3.project(`Target ${target}`, {".azuredevops/pull_request_template.md": template});
    const git = (...args: string[]) => sh("git", args, project);
    const commit = (message: string) => { git("add", "."); git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", message); };
    git("remote", "add", "origin", process.env.PROOF_REPO_URL!);
    git("config", "credential.helper", helper);
    if (target === "main") {
      git("push", "--force", "origin", "main");
      git("checkout", "-b", "release");
      writeFileSync(join(project,".azuredevops/pull_request_template.md"), "## Release-only Context\n\n## Release-only Verification\n");
      commit("Use distinct release template");
      git("push", "--force", "origin", "release");
      git("checkout", "main");
    } else {
      git("fetch", "origin", "main", "release");
      git("reset", "--hard", "origin/release");
    }
    git("fetch", "origin", "main", "release");
    git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main");
    const branch = `proof-${target}-${Date.now()}`;
    git("checkout", "-b", branch);
    writeFileSync(join(project,"feature.txt"), "Template proof feature\n");
    commit("Add feature documentation");
    git("push", "-u", "origin", "HEAD");
    git("config", `branch.${branch}.t3-merge-base-ref`, `refs/remotes/origin/${target}`);
    const thread = await t3.thread({project, title:`PR targeting ${target}`, messages:["Document the feature."]});
    fixtures.push({target,thread});
  }
  const descriptions = [];
  for (const {target,thread} of fixtures) {
    await t3.open(thread);
    await screen.getByRole("button", "Create PR", {exact:true}).tap();
    await screen.getByText("Created PR", {exact:false}).waitFor({state:"visible",timeout:150000});
    await screen.getByRole("button", /^https:\/\/dev\.azure\.com\/.*pullrequest/i).first().tap();
    const description = browser.locator("[data-pr-description]");
    await description.waitFor({state:"visible", timeout:60000});
    await app.screenshot(`description-target-${target}`);
    const body = await description.textContent();
    descriptions.push({target, context:body.includes("Template Context"), verification:body.includes("Template Verification"), releaseTemplate:body.includes("Release-only")});
  }
  expect(descriptions).toEqual(["main","release"].map(target=>({target,context:true,verification:true,releaseTemplate:false})));
});
