import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";

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

async function diskImage(name: string) {
  return runPromise(
    Effect.gen(function* () {
      const fs = yield* FileSystem.FileSystem;
      const path = yield* Path.Path;
      const fixture = yield* path.fromFileUrl(
        new URL(
          `../../apps/web/test/fixtures/disk-images/${name}`,
          import.meta.url,
        ),
      );
      return Buffer.from(yield* fs.readFile(fixture));
    }),
  );
}

test(
  "A disk image preview still opens a readable volume after an unreadable catalog",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo", { "intact.dmg": await diskImage("empty-first-volume.dmg"), "installer.dmg": await diskImage("unreadable-first-catalog.dmg") });
    const thread = await t3.thread({ project, title: "Disk image preview", messages: ["Ready"] });
    await t3.open(thread);
    await screen.getByTestId("composer-editor").waitFor();
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill("intact.dmg");
    await browser.locator('[role="option"] strong').filter({ hasText: "intact.dmg" }).first().waitFor();
    await screen.getByRole("option", "intact.dmg", { exact: false }).tap();
    await screen.getByRole("button", "Demo.app", { exact: true }).waitFor();
    await screen.getByRole("button", "Hide file explorer", { exact: true }).tap();
    await app.screenshot("intact-control");
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill("installer.dmg");
    await browser.locator('[role="option"] strong').filter({ hasText: "installer.dmg" }).first().waitFor();
    await screen.getByRole("option", "installer.dmg", { exact: false }).tap();
    const result = screen.getByText(/^(Demo\.app|This disk image is damaged\.)$/);
    await result.waitFor({ timeout: 120_000 });
    try {
      expect(await result.textContent()).toBe("Demo.app");
    } finally {
      await app.screenshot("disk-image-with-unreadable-first-catalog");
    }
  },
);
