import { AlqoveClient, createCheckinEndpoints } from "@alqove/api-client";

/**
 * Read the optional logged-in bearer token from localStorage.
 *
 * The check-in lane is a public, anonymous surface (D5/D10) — it must work with
 * no session at all. This is read-once-per-call and never throws: on the server
 * / edge there is no `window`, so it returns null and the lane stays anonymous.
 * Only the client `CheckinForm` submit uses the value (passed as `authToken`);
 * the branding shell never reads it.
 */
function readOptionalAuthToken(): string | null {
  if (typeof window === "undefined") return null;
  try {
    return localStorage.getItem("auth_token");
  } catch {
    // Private-mode / blocked storage — treat as anonymous.
    return null;
  }
}

/**
 * A dedicated client for the public check-in lane, intentionally separate from
 * the buyer `api` client so the lane never depends on the buyer auth flow. Its
 * `getToken` returns the optional session token when present, or null.
 */
const checkinClient = new AlqoveClient({
  baseUrl: process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000",
  getToken: readOptionalAuthToken,
});

export const checkinApi = createCheckinEndpoints(checkinClient);

/** Read the current optional auth token (null when anonymous). */
export const getOptionalAuthToken = readOptionalAuthToken;
