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

function stripSitePrefix(handle, site) {
  const normalizedHandle = normalizeIdentityValue(handle);
  const normalizedSite = normalizeIdentityValue(site);
  if (normalizedHandle && normalizedSite && normalizedHandle.startsWith(normalizedSite)) {
    return normalizeIdentityValue(normalizedHandle.slice(normalizedSite.length));
  }
  return normalizedHandle;
}

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

  try {
    const parsedUrl = new URL(normalizedUrl);
    const site = normalizeIdentityValue(
      parsedUrl.searchParams.get("siteid")
        || parsedUrl.searchParams.get("site")
        || parsedUrl.searchParams.get("fromSite"),
    );
    const handle = normalizeIdentityValue(
      parsedUrl.searchParams.get("touid")
        || parsedUrl.searchParams.get("uid")
        || parsedUrl.searchParams.get("toUser")
        || parsedUrl.searchParams.get("loginId"),
    );
    return {
      handle: stripSitePrefix(handle, site),
      site,
    };
  } 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),
  };
}
