/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const zone = (name: string) => execFileSync("sudo", ["-n", "ln", "-snf", `/usr/share/zoneinfo/${name}`, "/etc/localtime"]);

test("One-time schedule dates follow a system time zone change without reload", WEB, async ({ t3, app, browser, screen }) => {
  zone("America/New_York");
  try {
    const project = await t3.project("demo");
    const thread = await t3.thread({ project, title: "Zone probe", messages: ["Start"] });
    await t3.open(thread);
    await t3.open("/settings/scheduled-tasks");
    await screen.getByRole("button", "New task", { exact: true }).click();
    await browser.locator("#scheduled-task-title").fill("Zone probe");
    await browser.locator("#scheduled-task-prompt").fill("say hi");
    await screen.getByRole("button", "Once", { exact: true }).click();
    const local = await browser.locator("#scheduled-task-run-at").getAttribute("value");
    await screen.getByRole("button", "Create task", { exact: true }).click();
    await screen.getByText(/^Once, /).waitFor();
    await app.screenshot("new-york-before-zone-change");
    const instant = await browser.evaluate((value) => new Date(value!).toISOString(), local);
    zone("Asia/Bangkok");
    // Linux Chromium observes /etc/localtime changes asynchronously.
    for (let i = 0; i < 100; i++) {
      if (await browser.evaluate(() => Intl.DateTimeFormat().resolvedOptions().timeZone) === "Asia/Bangkok") break;
      await new Promise((resolve) => setTimeout(resolve, 100));
    }
    const currentZone = await browser.evaluate(() => Intl.DateTimeFormat().resolvedOptions().timeZone);
    if (currentZone !== "Asia/Bangkok") throw new Error(`System zone was not observed: ${currentZone}`);
    await screen.getByRole("button", "General", { exact: true }).click();
    await screen.getByRole("button", "Scheduled tasks", { exact: true }).click();
    await screen.getByText(/^Once, /).waitFor();
    const expected = await browser.evaluate((iso) => new Intl.DateTimeFormat("en-US", {dateStyle: "medium", timeStyle: "short"}).format(new Date(iso)), instant);
    await app.screenshot("bangkok-reopened-without-reload");
    await expect(screen.getByText(/^Once, /)).toContainText(`Once, ${expected}`);
  } finally {
    zone("Etc/UTC");
  }
});
