/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const source = (interval: string) => `const { workflow, every, Tick } = T3;
export default workflow("tick", { version: 1, payload: Tick, triggers: [every(${interval})] },
  Effect.fn(function* (payload) { return { at: payload.scheduledAt }; }));\n`;

test("Bigint nanoseconds load and validate as workflow intervals", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("workflow-demo");
  const write = (interval: string) => runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    yield* fs.makeDirectory(path.join(T3_HOME, "workflows"), { recursive: true });
    yield* fs.writeFileString(path.join(T3_HOME, "workflows/tick.ts"), source(interval));
  }));
  const renderedSource = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return "";
  });
  await write("60_000_000_000n");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
  }).pipe(Effect.scoped));
  await t3.open("/workflows?definitions=true&file=tick.ts");
  await screen.getByRole("button", "Definitions").waitFor({ timeout: 90_000 });
  await expect.poll(renderedSource, { timeout: 60_000 }).toContain("60_000_000_000n");
  await app.screenshot("one-minute-bigint");
  const first = await browser.evaluate(() => document.body.innerText);
  await write("1_000n");
  await expect.poll(renderedSource).toContain("every(1_000n)");
  await app.screenshot("subminimum-bigint");
  const second = await browser.evaluate(() => document.body.innerText);
  await write('"1 minute"');
  await expect.poll(renderedSource).toContain('every("1 minute")');
  await expect(screen.getByText("The file on disk does not load.", { exact: false })).not.toBeVisible();
  await app.screenshot("string-control");
  expect(first).not.toContain("Do not know how to serialize a BigInt");
  expect(second).toContain("every(1000n) is shorter than the shortest, one minute.");
});
