function normalizeIdentityValue(value) {
  return typeof value === "string" ? value.trim() : "";
}

export function parseWangwangContactIdentity(contactUrl) {
  const normalizedUrl = normalizeIdentityValue(contactUrl);
  if (!normalizedUrl) {
    return { handle: "", site: "" };
  }

  try {
    const parsedUrl = new URL(normalizedUrl);
    return {
      handle: normalizeIdentityValue(
        parsedUrl.searchParams.get("uid")
          || parsedUrl.searchParams.get("toUser")
          || parsedUrl.searchParams.get("loginId"),
      ),
      site: normalizeIdentityValue(
        parsedUrl.searchParams.get("site")
          || parsedUrl.searchParams.get("fromSite"),
      ),
    };
  } catch {
    return { handle: "", site: "" };
  }
}

export function resolveChatTaskContactIdentity(chatTask = {}) {
  const parsedIdentity = parseWangwangContactIdentity(chatTask.contact_url);
  const explicitHandle = normalizeIdentityValue(chatTask.contact_handle);
  const explicitSite = normalizeIdentityValue(chatTask.contact_site);

  return {
    handle: explicitHandle || parsedIdentity.handle,
    site: explicitSite && explicitSite !== "1688"
      ? explicitSite
      : (parsedIdentity.site || explicitSite),
    url: normalizeIdentityValue(chatTask.contact_url),
  };
}