import type { PostPerformance, PublishHealth } from "../api/haixun";
import { safeGetItem, safeSetItem } from "./safeStorage";

export const PUBLISH_PAGE_CACHE_TTL_MS = 5 * 60 * 1000;

const KEY_PREFIX = "haixun.publish.page.";

type CachedSnapshot = {
  cachedAt: number;
  performance?: PostPerformance;
  health?: PublishHealth;
};

function cacheKey(accountId: string) {
  return `${KEY_PREFIX}${accountId}`;
}

export function readPublishPageCache(accountId: string): CachedSnapshot | null {
  const id = accountId.trim();
  if (!id) return null;
  try {
    const raw = safeGetItem(cacheKey(id));
    if (!raw) return null;
    const parsed = JSON.parse(raw) as CachedSnapshot;
    if (!parsed || typeof parsed.cachedAt !== "number") return null;
    return parsed;
  } catch {
    return null;
  }
}

export function writePublishPageCache(
  accountId: string,
  data: { performance?: PostPerformance; health?: PublishHealth; cachedAt?: number }
) {
  const id = accountId.trim();
  if (!id) return;
  const snapshot: CachedSnapshot = {
    cachedAt: data.cachedAt ?? Date.now(),
    performance: data.performance,
    health: data.health
  };
  safeSetItem(cacheKey(id), JSON.stringify(snapshot));
}

export function isPublishPageCacheFresh(cachedAt: number, now = Date.now()) {
  if (!cachedAt) return false;
  return now - cachedAt < PUBLISH_PAGE_CACHE_TTL_MS;
}
