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

test("Advanced background edits save without false errors", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("background-settings");
  const thread = await t3.thread({ project, title: "Settings proof", messages: ["Start"] });
  await t3.open(thread);
  await t3.open("/settings/maintenance");
  await screen.getByRole("combobox", "Background activity profile").tap({ timeout: 90_000 });
  await screen.getByRole("option", "Advanced", { exact: true }).tap();
  const dialog = screen.getByRole("dialog", "Background Activity");
  const saved = async () => JSON.parse(await readFile(`${T3_HOME}/userdata/settings.json`, "utf8")).backgroundActivity;
  const errors: boolean[] = [];
  await dialog.getByRole("button", "Increase Git fetch interval", { exact: true }).tap();
  await expect.poll(async () => (await saved())?.overrides?.automaticGitFetchInterval).toBe(35000);
  await dialog.getByLabel("Git fetch interval in seconds").waitFor();
  await app.screenshot("interval-saved");
  errors.push(await screen.getByText("Setting not saved", { exact: true }).isVisible());
  await dialog.getByRole("switch", "Pause on battery", { exact: true }).tap();
  await expect.poll(async () => (await saved())?.overrides?.pauseWhenOnBattery).toBe(true);
  await app.screenshot("pause-on-battery-saved");
  errors.push(await screen.getByText("Setting not saved", { exact: true }).first().isVisible());
  await dialog.getByRole("switch", "Pause on battery", { exact: true }).tap();
  await expect.poll(async () => (await saved())?.overrides?.pauseWhenOnBattery).toBe(undefined);
  await app.screenshot("toggle-back-to-preset-saved");
  errors.push(await screen.getByText("Setting not saved", { exact: true }).first().isVisible());
  expect(errors).toEqual([false, false, false]);
});
