const VOLATILE_REQUEST_QUERY_PARAMS = new Set([
  "ts",
  "timestamp",
  "_",
  "cb",
  "cachebuster",
  "rnd",
  "random",
  "sid",
  "session",
  "sessionid",
  "rid",
  "reqid",
  "auctionId",
  "bidId",
  "impId",
  "correlator",
  "ord"
]);

function buildObservedRequestFingerprintSource(details) {
  const url = new URL(details.url);
  const stableQueryParams = {};

  Array.from(url.searchParams.keys())
    .sort()
    .forEach((key) => {
      if (
        VOLATILE_REQUEST_QUERY_PARAMS.has(key) ||
        key === "gdpr" ||
        key === "gdpr_consent" ||
        key === "addtlConsent"
      ) {
        return;
      }

      stableQueryParams[key] = url.searchParams.getAll(key).sort();
    });

  return {
    origin: url.origin,
    pathname: url.pathname,
    method: details.method,
    type: details.type,
    thirdParty: details.thirdParty,
    consentParams: {
      gdpr: url.searchParams.get("gdpr"),
      gdpr_consent: url.searchParams.get("gdpr_consent"),
      addtlConsent: url.searchParams.get("addtlConsent")
    },
    stableQueryParams: stableQueryParams
  };
}

async function buildObservedRequestFingerprint(details) {
  return sha256Hex(
    stableStringify(buildObservedRequestFingerprintSource(details))
  );
}
