/**
 * Stable per-draft idempotency key for the check-in submit.
 *
 * The customer may double-submit, hit back, or retry on flaky cellular. The API
 * dedupes by `idempotency_key`, so the client must send the SAME key for the
 * same logical submission and only mint a fresh one once a submission succeeds
 * (or the draft is explicitly reset). We persist in localStorage keyed by the
 * link token so a reload mid-flow still replays safely.
 */

const PREFIX = "checkin:idem:";

export function idempotencyStorageKey(token: string): string {
  return `${PREFIX}${token}`;
}

/** Read storage defensively — private mode / blocked storage must not throw. */
function safeGet(key: string): string | null {
  if (typeof window === "undefined") return null;
  try {
    return localStorage.getItem(key);
  } catch {
    return null;
  }
}

function safeSet(key: string, value: string): void {
  if (typeof window === "undefined") return;
  try {
    localStorage.setItem(key, value);
  } catch {
    // Non-fatal — the in-memory key returned this call is still usable.
  }
}

/**
 * Return the stable idempotency key for this token, creating + persisting one on
 * first use. Subsequent calls return the same key until {@link resetIdempotencyKey}.
 */
export function getOrCreateIdempotencyKey(token: string): string {
  const storageKey = idempotencyStorageKey(token);
  const existing = safeGet(storageKey);
  if (existing) return existing;

  const fresh = crypto.randomUUID();
  safeSet(storageKey, fresh);
  return fresh;
}

/** Clear the persisted key so the next draft gets a fresh one (call post-submit). */
export function resetIdempotencyKey(token: string): void {
  if (typeof window === "undefined") return;
  try {
    localStorage.removeItem(idempotencyStorageKey(token));
  } catch {
    // Ignore — a stale key only risks a harmless idempotent replay.
  }
}
