/// <reference lib="dom" />
import { 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 short = "a".repeat(197) + ".ts";
const long = short + ".ts";
const source = (kind: string, length: number) => `// ${kind.toUpperCase()} FILE ${length} chars\nexport default T3.workflow("${kind}-workflow", { version: 1, payload: Schema.Struct({}) },\n  Effect.fn(function* () {}));\n`;
const suffix = " -- EDITED AFTER SELECTING LONG FILE";

test("Selecting the long definition opens and saves that exact file", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("demo");
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.makeDirectory(`${T3_HOME}/workflows`, { recursive: true });
    yield* fs.writeFileString(`${T3_HOME}/workflows/${short}`, source("short", 200));
    yield* fs.writeFileString(`${T3_HOME}/workflows/${long}`, source("long", 203));
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
  }).pipe(Effect.scoped));
  await t3.open("/workflows?definitions=true");
  await screen.getByRole("button", /long-workflow/).tap();
  const editorText = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return "";
  });
  // Wait for either real definition, so the base continues through Save as well.
  await screen.getByRole("button", "Delete", { exact: true }).waitFor();
  await browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const editor = host.shadowRoot?.querySelector<HTMLElement>("[contenteditable=true], textarea");
      if (editor) { editor.focus(); return; }
    }
  });
  await browser.keyboard.press("ControlOrMeta+Home");
  await browser.keyboard.press("End");
  await browser.keyboard.type(suffix);
  await screen.getByRole("button", "Save", { exact: true }).tap();
  await screen.getByText("Saved and running", { exact: true }).waitFor();
  await app.screenshot("selected-long-definition-saved");
  const selected = await browser.evaluate(() => new URL(location.href).searchParams.get("file"));
  const text = await editorText();
  const disk = await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    return { short: yield* fs.readFileString(`${T3_HOME}/workflows/${short}`), long: yield* fs.readFileString(`${T3_HOME}/workflows/${long}`) };
  }));
  expect({ selected, text: text.includes("LONG FILE 203 chars" + suffix), disk }).toEqual({
    selected: long, text: true,
    disk: { short: source("short", 200), long: source("long", 203).replace("203 chars", "203 chars" + suffix) },
  });
});
