/**
 * 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>();
const TEMPORARY_FALLBACK_PRODUCTS: Record<string, ProductDoc> = {
  // TODO(platform): remove this hardcoded invttrdg fallback after creating the
  // real product in the platform-service /products registry.
  invttrdg: {
    id: 'invttrdg',
    productId: 'invttrdg',
    displayName: 'Investment Trading',
    licensePrefix: 'INVTTRDG',
    packageName: 'com.bytelyst.invttrdg',
    defaultPlan: 'free',
    trialDays: 14,
    deviceLimits: {
      free: 1,
      pro: 3,
      enterprise: 10,
    },
    websiteUrl: 'https://invttrdg.bytelyst.com',
    status: 'active',
    createdAt: '2026-05-05T00:00:00.000Z',
    updatedAt: '2026-05-05T00:00:00.000Z',
  },
};

/**
 * 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) ?? TEMPORARY_FALLBACK_PRODUCTS[productId];
}

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

/** Get all cached products. */
export function getAllProducts(): ProductDoc[] {
  return [
    ...Array.from(productCache.values()),
    ...Object.values(TEMPORARY_FALLBACK_PRODUCTS).filter(product => !productCache.has(product.id)),
  ];
}

/**
 * Products visible to a given user ("my projects"). Admins/super_admins see
 * every product; everyone else sees only the products they own (`ownerId`).
 * Owner-less legacy products are NOT shown to non-admins (they belong to no one
 * in particular), which keeps a generic, multi-tenant deployment isolated.
 */
export function productsForUser(userId: string, isAdmin: boolean): ProductDoc[] {
  const all = getAllProducts();
  if (isAdmin) return all;
  return all.filter(p => p.ownerId === userId);
}

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