import { expect, type Page } from "@playwright/test";
import { strToU8, zipSync } from "fflate";

export function sampleEpub(title: string) {
  return Buffer.from(zipSync({
    mimetype: strToU8("application/epub+zip"),
    "META-INF/container.xml": strToU8(`<?xml version="1.0"?>
      <container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0">
        <rootfiles><rootfile full-path="OPS/package.opf" media-type="application/oebps-package+xml"/></rootfiles>
      </container>`),
    "OPS/package.opf": strToU8(`<?xml version="1.0"?>
      <package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="id">
        <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
          <dc:identifier id="id">urn:hearbooks:e2e:${title}</dc:identifier>
          <dc:title>${title}</dc:title>
          <dc:creator>端到端验收作者</dc:creator>
        </metadata>
        <manifest>
          <item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>
          <item id="c1" href="chapter-1.xhtml" media-type="application/xhtml+xml"/>
          <item id="c2" href="chapter-2.xhtml" media-type="application/xhtml+xml"/>
        </manifest>
        <spine><itemref idref="c1"/><itemref idref="c2"/></spine>
      </package>`),
    "OPS/nav.xhtml": strToU8(`<!doctype html><html xmlns="http://www.w3.org/1999/xhtml"><body>
      <nav epub:type="toc" xmlns:epub="http://www.idpf.org/2007/ops"><ol>
        <li><a href="chapter-1.xhtml">第一章</a></li><li><a href="chapter-2.xhtml">第二章</a></li>
      </ol></nav>
    </body></html>`),
    "OPS/chapter-1.xhtml": strToU8(`<!doctype html><html xmlns="http://www.w3.org/1999/xhtml"><body>
      <h1>第一章</h1><p>你好，这是中文端到端验收句。</p>
      <p>Hello, this is the English end-to-end sentence.</p>
      <table><tr><td>表格默认跳过</td><td>42</td></tr></table><p>E = mc² + ∑ αᵢ。</p>
    </body></html>`),
    "OPS/chapter-2.xhtml": strToU8(`<!doctype html><html xmlns="http://www.w3.org/1999/xhtml"><body>
      <h1>第二章</h1><p>下一章会被预生成。</p><p>The next chapter remains editable.</p>
    </body></html>`),
  }, { level: 0 }));
}

export async function importEpub(page: Page, title: string) {
  await page.goto("/import");
  const chooseButton = page.getByRole("button", { name: "选择 EPUB 或 PDF" });
  await expect(chooseButton).toBeEnabled();
  const fileChooser = page.waitForEvent("filechooser");
  await chooseButton.click();
  await (await fileChooser).setFiles({
    name: "hearbooks-e2e.epub",
    mimeType: "application/epub+zip",
    buffer: sampleEpub(title),
  });
  await expect(page.getByText("已通过本地格式检查")).toBeVisible();
  await page.getByRole("button", { name: "上传并解析" }).click();
  await page.waitForURL(/\/books\/[^/]+\/edit(?:\?.*)?$/, { timeout: 60_000 });
  await expect(page.getByRole("heading", { name: "可朗读正文" })).toBeVisible();
  return new URL(page.url()).pathname.split("/")[2];
}

export async function deleteBook(page: Page, bookId: string | null) {
  if (!bookId) return;
  const result = await page.evaluate(async (id) => {
    const response = await fetch(`/api/books/${id}`, {
      method: "DELETE",
      headers: { "x-confirm-delete": "DELETE" },
    });
    return response.status;
  }, bookId);
  expect([204, 404]).toContain(result);
}
