export const FINISHED_PROGRESS_THRESHOLD = 99;

export type LibraryReadingStatus = "want_to_read" | "reading" | "finished";

/** API may return progress as a number or numeric string. */
export function coerceProgressPercent(progress: unknown): number | null {
  if (progress == null || progress === "") return null;
  const n = typeof progress === "number" ? progress : Number(progress);
  if (!Number.isFinite(n)) return null;
  return n;
}

/**
 * @param started True when the user has a saved EPUB location (reader was used).
 */
export function deriveReadingStatus(
  progress: unknown,
  started = false,
): LibraryReadingStatus {
  const pct = coerceProgressPercent(progress);
  if (pct != null && pct >= FINISHED_PROGRESS_THRESHOLD) return "finished";
  if (pct != null && pct > 0) return "reading";
  if (started) return "reading";
  return "want_to_read";
}

export function normalizeProgressPercent(
  progress: unknown,
  readingStatus: LibraryReadingStatus,
): number | null {
  const pct = coerceProgressPercent(progress);
  if (readingStatus !== "reading" && readingStatus !== "finished") return null;
  if (pct == null || pct <= 0) return null;
  return Math.min(100, Math.max(0, Math.round(pct)));
}
