// Website-session counting — Usercentrics' own definition: a sliding
// 30-minute activity window. Every page load refreshes the window if
// it's still open; a page load that finds the window already expired
// starts a new session. So continuous browsing (page loads spaced less
// than 30 minutes apart) counts as exactly one session no matter how
// long it goes on, while a real gap of 30+ minutes between page loads
// starts a new one. Deliberately a separate cache from consent-store.ts
// (different lifecycle: this expires every 30 minutes regardless of
// consent state, consent persists ~12 months) but reuses the exact same
// storage-backend selection — localStorage by default, or the shared
// root-domain cookie when the install snippet carries
// data-consent-scope="shared" (this is what lets one session window
// carry across configured subdomains instead of each subdomain counting
// its own session against the tenant's pooled monthly quota).

import {
  type StorageBackend,
  backendAt,
  scopeToken,
  withLegacy,
} from "./consent-store";
import type { ConsentStoreConfig } from "./consent-store";

const SESSION_WINDOW_MS = 30 * 60 * 1000;
// cookieBackend's expiryDays param is generic (any storage, any TTL) —
// this is just 30 minutes expressed as a fraction of a day.
const SESSION_COOKIE_EXPIRY_DAYS = SESSION_WINDOW_MS / (24 * 60 * 60 * 1000);

interface SessionMarker {
  expiresAt: number;
  // The random id this browser made when the session started; sent with the
  // session beacon so each browser's session is counted once. Absent in a marker
  // written by an older script.
  id?: string;
}

/** 16 random bytes as hex, or undefined where the browser cannot make them. */
function newSessionId(): string | undefined {
  try {
    const bytes = new Uint8Array(16);
    window.crypto.getRandomValues(bytes);
    return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
  } catch {
    return undefined;
  }
}

function backendFor(config: ConsentStoreConfig): StorageBackend {
  // Namespaced by the consent scope's token, like the consent record itself: two
  // different tenants can add the same root hostname, and without this namespace
  // activity under one would suppress the other's first-session beacon. The marker
  // under its earlier name (__consent_hub_sess_<token>__) is still read, so an active
  // visitor keeps their session id across the upgrade (a new id would count the same
  // browsing session again, as the server deduplicates by id).
  const token = scopeToken(config);
  return withLegacy(
    backendAt(config, `saasaudit-session-${token}`, SESSION_COOKIE_EXPIRY_DAYS),
    backendAt(
      config,
      `__consent_hub_sess_${token}__`,
      SESSION_COOKIE_EXPIRY_DAYS,
    ),
  );
}

function readMarker(config: ConsentStoreConfig): SessionMarker | null {
  const raw = backendFor(config).get();
  if (!raw) return null;
  try {
    return JSON.parse(raw) as SessionMarker;
  } catch {
    return null;
  }
}

function writeMarker(config: ConsentStoreConfig, marker: SessionMarker): void {
  backendFor(config).set(JSON.stringify(marker));
}

/** Called once per page load (from loader.ts's init()) — a sliding
 * 30-minute window, matching Usercentrics' own semantics exactly:
 *
 * - No cached marker, or the cached one has already expired: this load
 *   starts a NEW session — fires onNewSession() and writes a fresh
 *   30-minute marker. (Scenario B — a 45-minute break — the returning
 *   page load finds an expired marker and counts as session #2.)
 * - A cached marker that's still live: this load is inside an
 *   already-open session — no new beacon, but the marker's expiry is
 *   still refreshed to now + 30 minutes. This is what makes continuous
 *   browsing (Scenario C — an hour of clicking through pages, each
 *   load landing well within the still-open window) count as exactly
 *   ONE session even though it spans far longer than 30 minutes: every
 *   page load keeps pushing the expiry forward, so the window only
 *   ever lapses during a genuine gap in activity.
 * - A page load with no further page load for 30+ minutes (the visitor
 *   left the tab open but idle, or closed it) naturally lets the
 *   marker expire on its own — nothing needs to actively watch for
 *   this, since the check only ever runs on the next real page load.
 */
export function trackSession(
  config: ConsentStoreConfig,
  onNewSession: (sessionId?: string) => void,
): void {
  const cached = readMarker(config);
  const isNewSession = !cached || Date.now() >= cached.expiresAt;
  const id = isNewSession ? newSessionId() : cached?.id;
  writeMarker(config, {
    expiresAt: Date.now() + SESSION_WINDOW_MS,
    ...(id ? { id } : {}),
  });
  if (isNewSession) onNewSession(id);
}
