// Data-package staleness (ADR-005 follow-up). The genshin-db data package is a
// local snapshot; when a new Genshin version ships new sets/characters, an old
// package silently fails to recognize them. We cannot query the live game version
// offline, so staleness is based on the package's generation age: Genshin patches
// land roughly every six weeks, so a package older than ~45 days likely predates
// a content patch and should be regenerated with `npm run data:genshin`.

const DAY_MS = 24 * 60 * 60 * 1000;
export const DEFAULT_MAX_AGE_DAYS = 45;

export function dataPackageAgeDays(generatedAt: string, now: number = Date.now()): number | null {
  if (!generatedAt) return null;
  const generated = Date.parse(generatedAt);
  if (!Number.isFinite(generated)) return null;
  const age = (now - generated) / DAY_MS;
  return age < 0 ? 0 : Math.floor(age);
}

export interface DataPackageStatus {
  ageDays: number | null;
  stale: boolean;
  warning: string;
}

export function dataPackageStatus(
  generatedAt: string,
  sourceVersion: string,
  now: number = Date.now(),
  maxAgeDays: number = DEFAULT_MAX_AGE_DAYS,
): DataPackageStatus {
  const ageDays = dataPackageAgeDays(generatedAt, now);
  if (ageDays === null) {
    return {
      ageDays: null,
      stale: false,
      warning: "",
    };
  }
  const stale = ageDays > maxAgeDays;
  return {
    ageDays,
    stale,
    warning: stale
      ? `Datenpaket (${sourceVersion}) ist ${ageDays} Tage alt. Neue Sets/Charaktere fehlen evtl. - mit "npm run data:genshin" aktualisieren.`
      : "",
  };
}
