/**
 * Products in-memory cache.
 * Loaded on startup, refreshed after admin writes.
 */

import * as repository from './repository.js';
import type { ProductDoc } from './types.js';

const productCache = new Map<string, ProductDoc>();

/**
 * Load all products from Cosmos into memory.
 * Called on startup and after admin create/update.
 */
export async function loadProductCache(): Promise<void> {
  const all = await repository.getAll();
  productCache.clear();
  for (const p of all) productCache.set(p.id, p);
}

/** Get a product by ID from cache. */
export function getProduct(productId: string): ProductDoc | undefined {
  return productCache.get(productId);
}

/** Check if a productId exists in cache. */
export function isValidProduct(productId: string): boolean {
  return productCache.has(productId);
}

/** Get all cached products. */
export function getAllProducts(): ProductDoc[] {
  return Array.from(productCache.values());
}

/** Current cache size (for tests/health). */
export function cacheSize(): number {
  return productCache.size;
}
