import { isLiquidityPayload, type LiquidityPayload } from "./liquidity";
import { DEFAULT_CHAIN, type ChainId } from "./chains";

export const snapshotStorageKey = (chain: ChainId) => `amm-correlated-pairs-snapshot-v3:${chain}`;

export function storedSnapshot(chain: ChainId = DEFAULT_CHAIN.id): LiquidityPayload | null {
  try {
    const data: unknown = JSON.parse(localStorage.getItem(snapshotStorageKey(chain)) ?? "null");
    return isLiquidityPayload(data) && data.chainId === chain ? data : null;
  } catch { return null; }
}

export function saveSnapshot(data: LiquidityPayload, chain: ChainId = DEFAULT_CHAIN.id) {
  try {
    const current = storedSnapshot(chain);
    if (!current || Date.parse(data.updatedAt) >= Date.parse(current.updatedAt)) localStorage.setItem(snapshotStorageKey(chain), JSON.stringify({ ...data, chainId: chain }));
  } catch { /* Storage is optional. */ }
}

