import { OwnPostFormulaReview } from "../api/haixun";

export const FORMULA_CACHE_TTL_MS = 5 * 60 * 1000;

export function formulaReviewedAtMs(formula?: OwnPostFormulaReview): number {
  const raw = formula?.reviewed_at || 0;
  if (!raw) return 0;
  return raw > 1_000_000_000_000 ? raw / 1_000_000 : raw;
}

export function isFormulaFresh(formula?: OwnPostFormulaReview, now = Date.now()): boolean {
  const reviewedAt = formulaReviewedAtMs(formula);
  if (!reviewedAt) return false;
  return now - reviewedAt < FORMULA_CACHE_TTL_MS;
}

export function isFormulaStale(formula?: OwnPostFormulaReview, now = Date.now()): boolean {
  const reviewedAt = formulaReviewedAtMs(formula);
  if (!reviewedAt) return false;
  return now - reviewedAt >= FORMULA_CACHE_TTL_MS;
}

export function formulaCacheHint(formula?: OwnPostFormulaReview): string {
	if (!formula?.reviewed_at) return "";
	return "已儲存覆盤，可手動重新分析";
}

export function formatFormulaAge(formula?: OwnPostFormulaReview, now = Date.now()): string {
  const reviewedAt = formulaReviewedAtMs(formula);
  if (!reviewedAt) return "時間未知";
  const diffMin = Math.max(0, Math.floor((now - reviewedAt) / 60_000));
  if (diffMin < 1) return "剛剛";
  if (diffMin < 60) return `${diffMin} 分鐘前`;
  const diffHour = Math.floor(diffMin / 60);
  if (diffHour < 24) return `${diffHour} 小時前`;
  return `${Math.floor(diffHour / 24)} 天前`;
}

export type FormulaDisplayStatus = "loading" | "stored" | "fresh";

export function formulaDisplayStatus(
  formula?: OwnPostFormulaReview,
  refreshing = false,
  now = Date.now()
): FormulaDisplayStatus {
	if (refreshing) return "loading";
	if (!formula) return "fresh";
	return "stored";
}
