import type { HunterSave, SaveSlotState } from "./types";

export type SaveContinuation = "create" | "local" | "online" | "choose";

function saveTimestamp(save: HunterSave): number | null {
  const timestamp = Date.parse(save.updatedAt);
  return Number.isFinite(timestamp) ? timestamp : null;
}

export function resolveSaveContinuation(slot: Pick<SaveSlotState, "local" | "online">): SaveContinuation {
  if (!slot.local) return slot.online ? "online" : "create";
  if (!slot.online) return "local";

  const localTimestamp = saveTimestamp(slot.local);
  const onlineTimestamp = saveTimestamp(slot.online);
  if (localTimestamp !== null && onlineTimestamp !== null && onlineTimestamp > localTimestamp) return "choose";
  return "local";
}

export function saveVersionsMatch(local: HunterSave | null, online: HunterSave | null): boolean {
  return Boolean(local && online && local.slotId === online.slotId && local.updatedAt === online.updatedAt);
}
