import assert from "node:assert/strict";
import test from "node:test";
import { strFromU8, unzipSync } from "fflate";
import { buildRecoveryWorkbook } from "../lib/recovery-workbook.ts";

const tinyPng = Uint8Array.from([
  0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
  0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
  0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
]);

test("creates an xlsx archive whose pictures are embedded in worksheet cells", () => {
  const workbook = buildRecoveryWorkbook({
    sheetName: "数据回收",
    headers: ["序号", "标题", "原图", "笔记截图"],
    columnWidths: [8, 24, 24, 24],
    rows: [
      {
        cells: [1, "测试笔记", "", ""],
        images: [
          {
            column: 2,
            image: {
              bytes: tinyPng,
              contentType: "image/png",
              width: 1,
              height: 1,
              description: "原图1",
            },
          },
          {
            column: 3,
            image: {
              bytes: tinyPng,
              contentType: "image/png",
              width: 1,
              height: 1,
              description: "发布截图",
            },
          },
        ],
      },
    ],
  });
  const archive = unzipSync(workbook);
  const worksheet = strFromU8(archive["xl/worksheets/sheet1.xml"]);

  assert.ok(archive["xl/media/image1.png"]);
  assert.ok(archive["xl/media/image2.png"]);
  assert.match(worksheet, /<drawing r:id="rId1"\/>/);
  assert.doesNotMatch(worksheet, /#VALUE!/);
  const drawing = strFromU8(archive["xl/drawings/drawing1.xml"]);
  assert.equal((drawing.match(/<xdr:twoCellAnchor editAs="twoCell">/g) ?? []).length, 2);
  assert.match(drawing, /<xdr:col>2<\/xdr:col>/);
  assert.match(drawing, /<xdr:col>3<\/xdr:col>/);
  assert.match(
    strFromU8(archive["xl/drawings/_rels/drawing1.xml.rels"]),
    /image2\.png/,
  );
  assert.doesNotMatch(
    worksheet,
    /见图/,
  );
});

test("creates clickable external hyperlinks for resource exports", () => {
  const workbook = buildRecoveryWorkbook({
    sheetName: "KOC资源库",
    headers: ["账号名称", "账号主页"],
    columnWidths: [20, 40],
    rows: [
      {
        cells: ["小满的轻生活", "https://www.xiaohongshu.com/user/profile/test?x=1&y=2"],
        images: [],
        hyperlinks: [
          {
            column: 1,
            url: "https://www.xiaohongshu.com/user/profile/test?x=1&y=2",
          },
        ],
      },
    ],
  });
  const archive = unzipSync(workbook);
  const sheet = strFromU8(archive["xl/worksheets/sheet1.xml"]);
  const relationships = strFromU8(
    archive["xl/worksheets/_rels/sheet1.xml.rels"],
  );

  assert.match(sheet, /<hyperlink ref="B2" r:id="rId1"\/>/);
  assert.match(sheet, /<c r="B2" t="inlineStr" s="5">/);
  assert.match(relationships, /relationships\/hyperlink/);
  assert.match(relationships, /TargetMode="External"/);
  assert.match(relationships, /x=1&amp;y=2/);
});
