/**
 * SET 50 — web-runtime stale-bundle detection (long-lived SPA tabs).
 * Orthogonal to Part T (extension skew) and SET 23b (engine meta version).
 */

export type WebVersionPayload = { buildId: string; generatedAt?: string };

export function parseWebVersion(json: unknown): WebVersionPayload | null {
  if (!json || typeof json !== 'object') return null;
  const buildId = (json as { buildId?: unknown }).buildId;
  if (typeof buildId !== 'string' || !buildId.trim()) return null;
  const generatedAt = (json as { generatedAt?: unknown }).generatedAt;
  return {
    buildId: buildId.trim(),
    generatedAt: typeof generatedAt === 'string' ? generatedAt : undefined,
  };
}

/** Show when remote id differs from self and user has not dismissed THIS remote id. */
export function shouldShowStaleBundleBanner(opts: {
  selfBuildId: string | null;
  remoteBuildId: string | null;
  dismissedRemoteBuildId: string | null;
}): boolean {
  const { selfBuildId, remoteBuildId, dismissedRemoteBuildId } = opts;
  if (!selfBuildId || !remoteBuildId) return false;
  if (selfBuildId === remoteBuildId) return false;
  if (dismissedRemoteBuildId === remoteBuildId) return false;
  return true;
}

export const STALE_BUNDLE_BANNER =
  'A newer app version is live — reload this tab';

export const STALE_BUNDLE_POLL_MS = 120_000;
