import test from "node:test";
import assert from "node:assert/strict";

const helpers = await import("../src/offer-normalizer.js").catch(() => ({}));

test("normalizeOfferRecord extracts contact handle and keeps core fields", () => {
  assert.equal(typeof helpers.normalizeOfferRecord, "function");

  const record = helpers.normalizeOfferRecord(
    {
      title: "新款16GB+1TB iphone 16Promax正品国补5G苹17Promax官方官网手机",
      offerUrl: "http://detail.m.1688.com/page/index.html?offerId=1019606203003",
      imageUrl: "https://cbu01.alicdn.com/img/example.jpg",
      merchantName: "东莞市瑞思创电子科技有限公司",
      merchantUrl: "http://shop38af415644a31.1688.com",
      contactUrl:
        "https://air.1688.com/app/ocms-fusion-components-1688/def_cbu_web_im/index.html?uid=%E7%91%9E%E6%80%9D%E5%88%9B%E7%94%B5%E5%AD%90&site=cnalichn&fromid=cnalichn&offerId=1019606203003"
    },
    3
  );

  assert.deepEqual(record, {
    index: 3,
    title: "新款16GB+1TB iphone 16Promax正品国补5G苹17Promax官方官网手机",
    offerUrl: "http://detail.m.1688.com/page/index.html?offerId=1019606203003",
    imageUrl: "https://cbu01.alicdn.com/img/example.jpg",
    merchantName: "东莞市瑞思创电子科技有限公司",
    merchantUrl: "http://shop38af415644a31.1688.com",
    contact: {
      type: "wangwang",
      url: "https://air.1688.com/app/ocms-fusion-components-1688/def_cbu_web_im/index.html?uid=%E7%91%9E%E6%80%9D%E5%88%9B%E7%94%B5%E5%AD%90&site=cnalichn&fromid=cnalichn&offerId=1019606203003",
      handle: "瑞思创电子",
      site: "cnalichn"
    }
  });
});

test("normalizeOfferRecord tolerates missing contact url", () => {
  assert.equal(typeof helpers.normalizeOfferRecord, "function");

  const record = helpers.normalizeOfferRecord(
    {
      title: "全包护镜新款苹果17手机壳适用iphone17promax防摔16新机情侣透明",
      offerUrl: "http://detail.m.1688.com/page/index.html?offerId=982264425046",
      imageUrl: "",
      merchantName: "深圳市福田区好益佳电子商行",
      merchantUrl: "http://shop7no47703o9344.1688.com",
      contactUrl: ""
    },
    1
  );

  assert.equal(record.contact.type, "unknown");
  assert.equal(record.contact.handle, "");
  assert.equal(record.contact.url, "");
  assert.equal(record.contact.site, "");
});
