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

import { parseWangwangContactIdentity, resolveChatTaskContactIdentity } from "../src/contact-identity.js";

test("parseWangwangContactIdentity 从旺旺 URL 提取 uid 和 site", () => {
  const identity = parseWangwangContactIdentity(
    "https://air.1688.com/app/ocms-fusion-components-1688/def_cbu_web_im/index.html?uid=%E6%B2%B3%E5%8C%97%E5%B7%A5%E6%88%90&site=cnalichn&offerId=994681636138",
  );

  assert.deepEqual(identity, {
    handle: "河北工成",
    site: "cnalichn",
  });
});

test("parseWangwangContactIdentity 从真实客服 URL 提取 touid 和 siteid", () => {
  const identity = parseWangwangContactIdentity(
    "https://air.1688.com/app/ocms-fusion-components-1688/def_cbu_web_im/index.html?touid=cnalichn%E6%BA%90%E4%B8%B0%E5%A1%91%E8%83%B6sj&siteid=cnalichn&status=1&portalId=&gid=&offerId=&itemsId=&spmid=a2615.2177701.0#/",
  );

  assert.deepEqual(identity, {
    handle: "源丰塑胶sj",
    site: "cnalichn",
  });
});

test("resolveChatTaskContactIdentity 在旧任务缺少 handle 时回退解析 URL", () => {
  const identity = resolveChatTaskContactIdentity({
    contact_url: "https://air.1688.com/app/ocms-fusion-components-1688/def_cbu_web_im/index.html?uid=%E5%85%A8%E5%86%A0%E5%AE%8F%E9%93%B8%E4%B8%9A&site=cnalichn",
    contact_handle: "",
    contact_site: "1688",
  });

  assert.deepEqual(identity, {
    handle: "全冠宏铸业",
    site: "cnalichn",
    url: "https://air.1688.com/app/ocms-fusion-components-1688/def_cbu_web_im/index.html?uid=%E5%85%A8%E5%86%A0%E5%AE%8F%E9%93%B8%E4%B8%9A&site=cnalichn",
  });
});

test("resolveChatTaskContactIdentity 保留显式的非占位 site", () => {
  const identity = resolveChatTaskContactIdentity({
    contact_url: "https://air.1688.com/app/ocms-fusion-components-1688/def_cbu_web_im/index.html?uid=%E6%B5%8B%E8%AF%95%E5%95%86%E5%AE%B6&site=cnalichn",
    contact_handle: "测试商家",
    contact_site: "cnalichn",
  });

  assert.deepEqual(identity, {
    handle: "测试商家",
    site: "cnalichn",
    url: "https://air.1688.com/app/ocms-fusion-components-1688/def_cbu_web_im/index.html?uid=%E6%B5%8B%E8%AF%95%E5%95%86%E5%AE%B6&site=cnalichn",
  });
});
