import type { CheckinAcceptedData } from "@alqove/api-client";

/**
 * Persist the signed status link on-device so the customer can re-reach their
 * check-in after closing the tab, and so a 409 "already submitted" can route
 * them to the existing status (D8). Keyed by the link token.
 */

const PREFIX = "checkin:status:";

export interface PersistedStatus {
  status_token: string | null;
  status_url: string;
  checkin_code: string | null;
}

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

/** Build the relative status path for a token + status token. */
export function statusPath(token: string, statusToken: string): string {
  return `/c/${token}/s/${statusToken}`;
}

export function persistStatus(
  token: string,
  accepted: CheckinAcceptedData,
): PersistedStatus {
  const record: PersistedStatus = {
    status_token: accepted.status_token,
    // Prefer the server-provided URL; fall back to the canonical path.
    status_url:
      accepted.status_url ||
      (accepted.status_token ? statusPath(token, accepted.status_token) : "#"),
    checkin_code: accepted.checkin_code,
  };
  if (typeof window !== "undefined") {
    try {
      localStorage.setItem(storageKey(token), JSON.stringify(record));
    } catch {
      // Non-fatal — the confirmation screen still shows the link this session.
    }
  }
  return record;
}

export function readPersistedStatus(token: string): PersistedStatus | null {
  if (typeof window === "undefined") return null;
  try {
    const raw = localStorage.getItem(storageKey(token));
    return raw ? (JSON.parse(raw) as PersistedStatus) : null;
  } catch {
    return null;
  }
}
