import { expect } from "e2e";
import { test, WEB, runPromise } from "./t3.ts";
import { run } from "./shell.ts";

test("Push honors configured fork and preserves origin tracking", WEB, async ({t3, app, screen}) => {
  const fixtures = [];
  for (const [name, setting] of [["Push default", "remote.pushDefault"], ["Branch push remote", "branch.topic.pushRemote"]]) {
    const project = await t3.project(name);
    const git = async (...args: string[]) => (await runPromise(run("git", args, {cwd: project}))).stdout.trim();
    await git("init", "--bare", "source.git");
    await git("init", "--bare", "fork.git");
    await git("remote", "add", "origin", "./source.git");
    await git("push", "origin", "main");
    await git("checkout", "-b", "topic");
    await git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", "Topic first commit");
    await git("push", "-u", "origin", "topic");
    await git("remote", "add", "fork", "./fork.git");
    await git("push", "fork", "topic");
    await git("fetch", "fork");
    await git("config", setting, "fork");
    const thread = await t3.thread({project, title: name, messages: ["Show repository status"]});
    await git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", "Second commit for fork");
    const local = await git("rev-parse", "HEAD");
    const source = await git("--git-dir=source.git", "rev-parse", "topic");
    fixtures.push({name, thread, git, local, source});
  }
  const results = [];
  for (const {name, thread, git, local, source} of fixtures) {
    await t3.open(thread);
    await screen.getByRole("button", "Git action options", {exact:true}).tap();
    await screen.getByRole("menuitem", "Push", {exact:true}).tap();
    await screen.getByText(/Pushed to /).waitFor({state:"visible"});
    await app.screenshot(name);
    results.push({setting:name, fork: await git("--git-dir=fork.git", "rev-parse", "topic"), expectedFork:local, source:await git("--git-dir=source.git", "rev-parse", "topic"), expectedSource:source, upstream:await git("rev-parse", "--abbrev-ref", "@{upstream}")});
  }
  await expect(results).toEqual(results.map(r => ({...r, fork:r.expectedFork, source:r.expectedSource, upstream:"origin/topic"})));
});
