import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Refresh diff fetches a remotely merged base with automatic fetch disabled", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("refresh-diff");
  const git = (cwd: string, args: string[]) => runPromise(run("git", args, { cwd }));
  const author = ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid"];
  const remote = `${project}-origin.git`;
  const other = `${project}-maintainer`;
  await git(project, ["init", "--bare", remote]);
  await git(project, ["remote", "add", "origin", remote]);
  await git(project, ["push", "-u", "origin", "main"]);
  await git(project, ["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main"]);
  await git(project, ["checkout", "-b", "feature"]);
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.writeFileString(`${project}/feature.txt`, "Feature line one\nFeature line two\nFeature line three\n");
    const settingsPath = `${T3_HOME}/userdata/settings.json`;
    const settings = JSON.parse(yield* fs.readFileString(settingsPath));
    settings.backgroundActivity = { schemaVersion: 1, profile: "custom", baseProfile: "balanced", overrides: { automaticGitFetchInterval: 0 } };
    yield* fs.writeFileString(settingsPath, JSON.stringify(settings));
  }));
  await git(project, ["add", "feature.txt"]);
  await git(project, [...author, "commit", "-m", "Add feature"]);
  await git(project, ["push", "-u", "origin", "feature"]);
  await git(project, ["clone", "--branch", "main", remote, other]);
  const thread = await t3.thread({ project, title: "Refresh merged branch", messages: ["first"] });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Diff", { exact: true }).tap();
  await screen.getByRole("button", "Expand feature.txt", { exact: true }).waitFor();
  await app.screenshot("before-remote-merge");
  await git(other, [...author, "merge", "--no-ff", "origin/feature", "-m", "Merge feature"]);
  await git(other, ["push", "origin", "main"]);
  await git(other, ["push", "origin", "--delete", "feature"]);
  await screen.getByRole("button", "Refresh diff", { exact: true }).tap();
  await screen.getByRole("button", "Refresh diff", { exact: true }).waitFor();
  try {
    await expect(screen.getByText("No net changes in this selection.", { exact: true })).toBeVisible();
  } finally {
    await app.screenshot("after-refresh-diff");
  }
});
