const WANGWANG_PATH_FRAGMENT = "def_cbu_web_im";

export function extractContactHandle(contactUrl) {
  if (!contactUrl) {
    return "";
  }

  try {
    const url = new URL(contactUrl);
    return url.searchParams.get("uid") ?? "";
  } catch {
    return "";
  }
}

export function extractContactSite(contactUrl) {
  if (!contactUrl) {
    return "";
  }

  try {
    const url = new URL(contactUrl);
    return url.searchParams.get("site") ?? "";
  } catch {
    return "";
  }
}

export function normalizeOfferRecord(rawRecord, index) {
  const contactUrl = rawRecord.contactUrl?.trim() ?? "";

  return {
    index,
    title: rawRecord.title?.trim() ?? "",
    offerUrl: rawRecord.offerUrl?.trim() ?? "",
    imageUrl: rawRecord.imageUrl?.trim() ?? "",
    merchantName: rawRecord.merchantName?.trim() ?? "",
    merchantUrl: rawRecord.merchantUrl?.trim() ?? "",
    contact: {
      type: contactUrl.includes(WANGWANG_PATH_FRAGMENT) ? "wangwang" : "unknown",
      url: contactUrl,
      handle: extractContactHandle(contactUrl),
      site: extractContactSite(contactUrl)
    }
  };
}
