import type { ThreadsMentionHit } from "./mentionInbox";

export const MENTION_INBOX_CACHE_TTL_MS = 5 * 60 * 1000;

export function mentionSyncedAtMs(syncedAt?: number): number {
  const raw = syncedAt || 0;
  if (!raw) return 0;
  return raw > 1_000_000_000_000 ? raw / 1_000_000 : raw;
}

export function mentionInboxCacheAgeMs(items: ThreadsMentionHit[], now = Date.now()): number | null {
  const stamps = items.map((item) => mentionSyncedAtMs(item.synced_at)).filter((value) => value > 0);
  if (!stamps.length) return null;
  const newest = Math.max(...stamps);
  return Math.max(0, now - newest);
}

export function isMentionInboxCacheFresh(items: ThreadsMentionHit[], now = Date.now()) {
  const age = mentionInboxCacheAgeMs(items, now);
  if (age === null) return false;
  return age < MENTION_INBOX_CACHE_TTL_MS;
}

export function isMentionInboxSyncedAtFresh(newestSyncedAt?: number, now = Date.now()) {
  const syncedMs = mentionSyncedAtMs(newestSyncedAt);
  if (!syncedMs) return false;
  return now - syncedMs < MENTION_INBOX_CACHE_TTL_MS;
}