/// <reference lib="dom" />
import { afterEach, expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";

import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const FILE = `${T3_HOME}/workflows/notes.ts`;
let workflowsEnabled: boolean | undefined;
afterEach(({ app }) =>
  runPromise(
    Effect.gen(function* () {
      yield* (yield* FileSystem.FileSystem).remove(FILE, { force: true });
      if (workflowsEnabled === undefined) return;
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["server.updateSettings"]({ patch: { workflowsEnabled } });
      workflowsEnabled = undefined;
    }).pipe(Effect.scoped),
  ),
);
const definition = (comment: string) => `// ${comment}
export default T3.workflow("notes", { version: 1, payload: Schema.Struct({}) },
  Effect.fn(function* () { return "Done"; }));
`;

test(
  "Undoing all edits shows the current workflow definition from disk",
  WEB,
  async ({ t3, app, browser, screen }) => {
    await t3.project("demo");
    const write = (comment: string) =>
      runPromise(
        Effect.flatMap(FileSystem.FileSystem, (fs) =>
          fs.writeFileString(FILE, definition(comment)),
        ),
      );
    await runPromise(
      Effect.flatMap(FileSystem.FileSystem, (fs) =>
        fs.makeDirectory(`${T3_HOME}/workflows`, { recursive: true }),
      ),
    );
    await write("Original notes");
    await runPromise(
      Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
        workflowsEnabled = (yield* client["server.getSettings"]({})).workflowsEnabled;
        yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
      }).pipe(Effect.scoped),
    );
    await t3.open("/workflows?definitions=true&file=notes.ts");
    await screen.getByRole("button", "Save", { exact: true }).waitFor();
    const focusEditor = () =>
      browser.evaluate(() => {
        for (const host of document.querySelectorAll("*")) {
          const editor = host.shadowRoot?.querySelector<HTMLElement>('[contenteditable="true"]');
          if (editor) {
            editor.focus();
            const line = editor.querySelector("[data-line]") ?? editor;
            const range = document.createRange();
            range.selectNodeContents(line);
            range.collapse(true);
            const selection = document.getSelection();
            selection?.removeAllRanges();
            selection?.addRange(range);
            return true;
          }
        }
        return false;
      });
    await expect.poll(focusEditor).toBe(true);
    await browser.keyboard.type(" ");
    await screen.getByText("Unsaved changes", { exact: true }).waitFor();

    await write("Notes updated on disk");
    await screen
      .getByText("The file changed on disk while you were editing.", { exact: false })
      .waitFor();
    await browser.keyboard.press("ControlOrMeta+z");
    await screen.getByText("Unsaved changes", { exact: true }).waitFor({ state: "hidden" });
    const editorText = () =>
      browser.evaluate(() => {
        for (const host of document.querySelectorAll("*")) {
          const content = host.shadowRoot?.querySelector("[data-content]");
          if (content) return content.textContent ?? "";
        }
        return "";
      });
    await app.screenshot("workflow-definition-after-undo");
    await expect.poll(editorText).toContain("Notes updated on disk");
  },
);
