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

import { runPromise, test, WEB } from "./t3.ts";

test(
  "The workspace editor tells the user when it cannot save their edit",
  WEB,
  async ({ t3, app, browser, screen }) => {
    await browser.setViewport({ width: 1600, height: 900 });
    const project = await t3.project("demo", { "notes.txt": "Original notes" });
    const path = `${project}/notes.txt`;
    const chmod = (mode: number) =>
      runPromise(Effect.flatMap(FileSystem.FileSystem, (fs) => fs.chmod(path, mode)));
    await browser.addInitScript(() => {
      const send = WebSocket.prototype.send;
      WebSocket.prototype.send = function (data) {
        if (typeof data === "string") {
          for (const message of [JSON.parse(data)].flat()) {
            if (message._tag !== "Request" || message.tag !== "projects.writeFile") continue;
            const onReply = (event: MessageEvent) => {
              if (typeof event.data !== "string") return;
              for (const reply of [JSON.parse(event.data)].flat()) {
                if (reply._tag !== "Exit" || String(reply.requestId) !== String(message.id))
                  continue;
                document.documentElement.dataset.fileWriteResult = reply.exit._tag;
                this.removeEventListener("message", onReply);
              }
            };
            this.addEventListener("message", onReply);
          }
        }
        send.call(this, data);
      };
    });

    await t3.open();
    await screen.getByRole("button", "New thread in demo", { exact: true }).tap();
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill("notes.txt");
    await screen.getByRole("option", "notes.txt", { exact: false }).tap();
    await browser.locator("diffs-container").waitFor({ state: "attached" });
    await expect
      .poll(() =>
        browser.evaluate(() => {
          const content = document
            .querySelector("diffs-container")
            ?.shadowRoot?.querySelector<HTMLElement>('[data-content][contenteditable="true"]');
          if (!content) return false;
          content.focus();
          return true;
        }),
      )
      .toBe(true);

    // Keep host access in the app, but take away the OS write bit for this file.
    await chmod(0o444);
    try {
      await browser.keyboard.press("ControlOrMeta+a");
      await browser.keyboard.type("Edited notes");
      await browser
        .locator('html[data-file-write-result="Failure"]')
        .waitFor({ state: "attached" });

      try {
        await expect(screen.getByText("Could not save file", { exact: true })).toBeVisible();
      } finally {
        await app.screenshot("editor-after-failed-autosave");
      }
    } finally {
      await chmod(0o644);
    }
  },
);
