/**
 * The buyer's GA4 client and session ids, read from gtag's cookies, so the
 * server can send the subscription's conversion to the same GA user and
 * session (and Google Ads can credit the ad click). Sent with checkout.
 *
 *   _ga=GA1.1.<client id: two numbers>
 *   _ga_<stream>=GS1.1.<session id>.<...>        (before 2025)
 *   _ga_<stream>=GS2.1.s<session id>$o<n>$...     (since 2025)
 */
export interface GaIds {
  ga_client_id: string;
  ga_session_id: string;
}

export function readGaIds(cookie: string): GaIds | null {
  const jar = new Map<string, string>();
  for (const part of cookie.split(";")) {
    const i = part.indexOf("=");
    if (i > 0) jar.set(part.slice(0, i).trim(), decodeURIComponent(part.slice(i + 1).trim()));
  }
  const ga = jar.get("_ga")?.split(".");
  if (!ga || ga.length < 4) return null;
  const clientId = ga.slice(-2).join(".");

  let sessionId = "";
  for (const [name, value] of jar) {
    if (!name.startsWith("_ga_")) continue;
    const gs2 = value.match(/^GS2\.\d+\.s(\d+)/);
    const gs1 = value.match(/^GS1\.\d+\.(\d+)\./);
    sessionId = gs2?.[1] ?? gs1?.[1] ?? "";
    if (sessionId) break;
  }
  return { ga_client_id: clientId, ga_session_id: sessionId };
}

/** readGaIds over document.cookie; null outside a browser. */
export function currentGaIds(): GaIds | null {
  try {
    return typeof document === "undefined" ? null : readGaIds(document.cookie);
  } catch {
    return null;
  }
}
