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

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

declare global {
  interface Window {
    releaseFirstNotesSave: () => void;
  }
}

test(
  "Closing an editor retries the newest draft if its first write fails",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo", { "notes.txt": "Original notes" });
    const thread = await t3.thread({ project, title: "Edit notes", messages: ["Start"], model: "default" });

    await browser.addInitScript(() => {
      const send = WebSocket.prototype.send;
      let writes = 0;
      WebSocket.prototype.send = function (data) {
        const request: {
          _tag?: string;
          tag?: string;
          id?: string;
          payload?: { cwd: string; relativePath: string; contents: string };
        } | null = typeof data === "string" ? JSON.parse(data) : null;
        if (
          request?._tag !== "Request" ||
          request.tag !== "projects.writeFile" ||
          request.payload?.relativePath !== "notes.txt"
        ) {
          return send.call(this, data);
        }
        const { cwd, relativePath } = request.payload;
        writes += 1;
        if (writes === 1) {
          window.releaseFirstNotesSave = () => send.call(this, data);
          document.documentElement.dataset.heldNotesSaveContents = request.payload.contents;
          return;
        }
        if (writes !== 2) return send.call(this, data);
        document.documentElement.dataset.failedNotesSaveContents = request.payload.contents;

        // The first follow-up fails once. Successful writes always reach the real filesystem.
        queueMicrotask(() => {
          this.dispatchEvent(
            new MessageEvent("message", {
              data: JSON.stringify({
                _tag: "Exit",
                requestId: request.id,
                exit: {
                  _tag: "Failure",
                  cause: [
                    {
                      _tag: "Fail",
                      error: {
                        _tag: "ProjectWriteFileError",
                        cwd,
                        relativePath,
                        message: "Temporary save failure.",
                      },
                    },
                  ],
                },
              }),
            }),
          );
        });
      };
    });

    await t3.open(thread);
    await screen
      .getByRole("button", "Fork from this response", { exact: true })
      .waitFor({ state: "attached" });
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill("notes.txt");
    await screen.getByRole("option", "notes.txt", { exact: false }).tap();
    const editor = browser.locator('[data-content][contenteditable="true"]');
    await editor.waitFor({ state: "visible", timeout: 30_000 });
    await editor.tap();
    await browser.keyboard.press("ControlOrMeta+a");
    await browser.keyboard.type("First draft");
    await browser
      .locator('html[data-held-notes-save-contents="First draft"]')
      .waitFor({ state: "attached" });
    await browser.keyboard.press("ControlOrMeta+a");
    await browser.keyboard.type("Final draft");
    const close = screen.getByRole("button", "Close notes.txt", { exact: true });
    await close.tap();
    await close.waitFor({ state: "hidden" });
    await browser.evaluate(() => {
      window.releaseFirstNotesSave();
      return null;
    });

    await browser
      .locator('html[data-failed-notes-save-contents="Final draft"]')
      .waitFor({ state: "attached" });
    const savedNotes = () =>
      runPromise(FileSystem.FileSystem.use((fs) => fs.readFileString(`${project}/notes.txt`)));
    try {
      const diffTab = screen.getByText("Diff", { exact: true });
      if (!(await diffTab.isVisible())) {
        await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
      }
      await diffTab.tap();
      await screen.getByRole("button", "Refresh diff", { exact: true }).tap();
      await screen.getByRole("button", "Expand all files", { exact: true }).tap();
      await browser
        .locator('[data-line-type="change-addition"]')
        .getByText(/^(First|Final) draft$/)
        .waitFor();
      await app.screenshot("saved-notes-in-working-tree-diff");
    } finally {
      // Runs after the capture so a missing save, not the capture, is the reported failure.
      await expect.poll(savedNotes).toBe("Final draft");
    }
  },
);
