import { AsyncLocalStorage } from 'node:async_hooks';

/**
 * Per-request cache metadata populated by CacheService.getOrSet.
 * Used by CacheMetaInterceptor to inject cacheMeta into analytics responses.
 */
export interface CacheMeta {
  /** ISO-8601 timestamp of when the cached value was stored. Null for pre-v1 cache entries. */
  cachedAt: string | null;
  /** ISO-8601 timestamp of when the cache entry will expire. Null for pre-v1 cache entries. */
  nextRefreshAt: string | null;
  /** Whether the data was served from cache or freshly fetched. */
  source: 'cache' | 'fresh';
}

export interface CacheMetaStore {
  meta: CacheMeta | null;
}

/**
 * AsyncLocalStorage context for per-request cache metadata propagation.
 * CacheService.getOrSet writes into this store; CacheMetaInterceptor reads from it.
 */
export const cacheMetaStorage = new AsyncLocalStorage<CacheMetaStore>();
