const latestTcfPingByTab = new Map();
const latestConsentStateByTabFrame = new Map();

function rememberLatestTcfPing(tabId, pingData) {
  latestTcfPingByTab.set(tabId, pingData);
}

function getLatestTcfPing(tabId) {
  return latestTcfPingByTab.get(tabId) ?? null;
}

function rememberLatestConsentState(consentState) {
  const key = buildTabFrameKey(
    consentState?.page?.tabId,
    consentState?.page?.frameId
  );

  if (key === null) {
    return;
  }

  latestConsentStateByTabFrame.set(key, {
    stateFingerprint: consentState.stateFingerprint,
    capturedAt: consentState.capturedAt,
    tabId: consentState.page.tabId,
    frameId: consentState.page.frameId
  });
}

function getLatestConsentStateForRequest(tabId, frameId) {
  const key = buildTabFrameKey(tabId, frameId);

  if (key === null) {
    return null;
  }

  return latestConsentStateByTabFrame.get(key) ?? null;
}

function buildTabFrameKey(tabId, frameId) {
  if (tabId === null || tabId === undefined || frameId === null || frameId === undefined) {
    return null;
  }

  return `${tabId}:${frameId}`;
}
