/**
 * Defensive helpers for Smartcar SDK return values.
 *
 * The Smartcar Node SDK has changed shape across versions (numeric `expiresIn`
 * in older releases, a `Date` `expiration` in v9+). We coerce both into a
 * single Mongoose-safe Date, and reject anything that would otherwise
 * become an `Invalid Date` and surface as a CastError on `tokenExpiresAt`.
 */
export function toValidDate(value: unknown): Date | null {
  if (value instanceof Date) {
    return Number.isFinite(value.getTime()) ? value : null;
  }
  if (typeof value === "number" && Number.isFinite(value)) {
    // Heuristic: a value smaller than ~Sep 2001 in ms is almost certainly a
    // "seconds from now" offset (the legacy `expiresIn` shape). Anything
    // larger is a unix-ms timestamp.
    const SECONDS_THRESHOLD_MS = 1_000_000_000_000;
    const ms =
      value < SECONDS_THRESHOLD_MS ? Date.now() + value * 1000 : value;
    const d = new Date(ms);
    return Number.isFinite(d.getTime()) ? d : null;
  }
  if (typeof value === "string" && value.length > 0) {
    const d = new Date(value);
    return Number.isFinite(d.getTime()) ? d : null;
  }
  return null;
}

/**
 * Resolve the access-token expiration from the (loosely-typed) Smartcar
 * SDK access object. Tries `expiration` (v9+) first, then falls back to
 * `expiresIn` (legacy seconds offset). Returns null if neither is usable.
 */
export function resolveSmartcarAccessExpiration(
  access: unknown
): Date | null {
  if (!access || typeof access !== "object") return null;
  const a = access as Record<string, unknown>;
  return toValidDate(a.expiration) ?? toValidDate(a.expiresIn);
}
