import { IEntityResolver } from './IEntityResolver';

/**
 * EntityResolver - Resolves entities from pre-loaded cache
 *
 * Entities must be loaded before use (typically at render time).
 * This allows synchronous lookups during filtering.
 */
export class EntityResolver implements IEntityResolver {
  private cache: Map<string, Map<string, Record<string, unknown>>> = new Map();

  /**
   * Load entities into cache for a given type
   * @param entityType - The entity type (e.g., 'resource')
   * @param entities - Array of entities with 'id' property
   */
  load<T extends { id: string }>(entityType: string, entities: T[]): void {
    const typeCache = new Map<string, Record<string, unknown>>();
    for (const entity of entities) {
      // Cast to Record for storage while preserving original data
      typeCache.set(entity.id, entity as unknown as Record<string, unknown>);
    }
    this.cache.set(entityType, typeCache);
  }

  /**
   * Resolve an entity by type and ID
   */
  resolve(entityType: string, id: string): Record<string, unknown> | undefined {
    const typeCache = this.cache.get(entityType);
    if (!typeCache) return undefined;
    return typeCache.get(id);
  }

  /**
   * Clear all cached entities
   */
  clear(): void {
    this.cache.clear();
  }

  /**
   * Clear cache for a specific entity type
   */
  clearType(entityType: string): void {
    this.cache.delete(entityType);
  }
}
