import assert from "node:assert/strict";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import test, { after } from "node:test";
import { Document, HeadingLevel, ImageRun, Packer, Paragraph, TextRun } from "docx";

const TEST_IMAGE = path.join(process.cwd(), "pic", "主页大图素材-1.png");
const UNIQUE_MARKER = "QIYOUXUE-IMPORT-TEST-20260812";
const dataDirectory = await fs.mkdtemp(path.join(os.tmpdir(), "qiyouxue-import-"));
process.env.CMS_DATA_DIR = dataDirectory;
process.env.CMS_BUILD_LOCK = path.join(dataDirectory, "site-build.lock");
process.env.CMS_API_KEY = "word-import-test-key";

const [{ handleCmsApi }, { GET: getUpload }] = await Promise.all([
  import("../src/lib/cms-api"),
  import("../src/pages/uploads/[file]"),
]);

after(async () => {
  await fs.rm(dataDirectory, { recursive: true, force: true });
});

function cmsRequest(route: string, method = "GET", body?: Record<string, unknown>, key = "word-import-test-key"): Request {
  return new Request(`http://localhost/api/cms/${route}`, {
    method,
    headers: {
      Authorization: `Bearer ${key}`,
      ...(body ? { "Content-Type": "application/json" } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
  });
}

async function wordDocument(): Promise<Buffer> {
  const png = await fs.readFile(TEST_IMAGE);
  const document = new Document({
    sections: [{
      children: [
        new Paragraph({ text: "Qiyouxue Word Import Test", heading: HeadingLevel.HEADING_1 }),
        new Paragraph({ children: [new TextRun(`Imported Word body marker: ${UNIQUE_MARKER}`)] }),
        new Paragraph({ children: [new ImageRun({ data: png, transformation: { width: 160, height: 105 }, type: "png" })] }),
      ],
    }],
  });
  return Packer.toBuffer(document);
}

test("imports a Markdown file payload as a draft", async () => {
  const markdown = `# 启优学 Markdown 导入测试\n\n这是 Markdown 上传测试：${UNIQUE_MARKER}`;
  const heading = markdown.match(/^#\s+(.+)$/m);
  assert.ok(heading?.index !== undefined);
  const body = `${markdown.slice(0, heading.index)}${markdown.slice(heading.index + heading[0].length)}`.trim();
  const response = await handleCmsApi(cmsRequest("articles", "POST", {
    title: heading[1],
    category: "学情指南",
    body,
  }), "articles");

  assert.equal(response.status, 201);
  const imported = await response.json();
  assert.equal(imported.publishStatus, "new-draft");

  const articleResponse = await handleCmsApi(cmsRequest(`articles/${imported.slug}`), `articles/${imported.slug}`);
  const article = await articleResponse.json();
  assert.equal(article.title, "启优学 Markdown 导入测试");
  assert.match(article.body, new RegExp(UNIQUE_MARKER));
  assert.doesNotMatch(article.body, /^#\s+/);
});

test("imports a docx with the requested embedded PNG as a Markdown draft", async () => {
  const buffer = await wordDocument();
  const response = await handleCmsApi(cmsRequest("imports/word", "POST", {
    fileName: "启优学导入测试.docx",
    category: "学习方法",
    dataUrl: `data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,${buffer.toString("base64")}`,
  }), "imports/word");

  assert.equal(response.status, 201);
  const imported = await response.json();
  assert.equal(imported.title, "Qiyouxue Word Import Test");
  assert.equal(imported.publishStatus, "new-draft");
  assert.equal(imported.imageCount, 1);

  const articleResponse = await handleCmsApi(cmsRequest(`articles/${imported.slug}`), `articles/${imported.slug}`);
  assert.equal(articleResponse.status, 200);
  const article = await articleResponse.json();
  assert.equal(article.category, "学习方法");
  assert.match(article.body, new RegExp(UNIQUE_MARKER));
  assert.doesNotMatch(article.body, /^#\s+Qiyouxue Word Import Test/m);

  const imageUrl = article.body.match(/!\[[^\]]*\]\((\/uploads\/[^)]+)\)/)?.[1];
  assert.ok(imageUrl);
  const filename = imageUrl.replace(/^\/uploads\//, "");
  const imageResponse = await getUpload({ params: { file: filename } } as never);
  assert.equal(imageResponse.status, 200);
  assert.equal(imageResponse.headers.get("content-type"), "image/png");
  assert.deepEqual(Buffer.from(await imageResponse.arrayBuffer()), await fs.readFile(TEST_IMAGE));
});

test("requires valid authentication for Word import", async () => {
  const response = await handleCmsApi(cmsRequest("imports/word", "POST", {}, "wrong-key"), "imports/word");
  assert.equal(response.status, 401);
});

test("rejects legacy .doc files", async () => {
  const response = await handleCmsApi(cmsRequest("imports/word", "POST", {
    fileName: "旧文章.doc",
    dataUrl: "data:application/octet-stream;base64,AA==",
  }), "imports/word");
  assert.equal(response.status, 400);
  assert.match((await response.json()).error, /不支持旧版 \.doc/);
});
