/**
 * ItemRegistry.js
 * Manages item definitions loaded from JSON files.
 * Similar to SkillRegistry pattern.
 */

import { Item } from "../items/Item.js";

export class ItemRegistry {
  constructor() {
    /** @type {Map<string, Item>} */
    this.items = new Map();

    /** @type {Promise<void> | null} */
    this.loadPromise = null;
  }

  /**
   * Loads all item definitions.
   * Uses a singleton promise to prevent duplicate loads.
   * @returns {Promise<void>}
   */
  async loadAll() {
    if (this.loadPromise) {
      return this.loadPromise;
    }

    this.loadPromise = this._doLoadAll();
    return this.loadPromise;
  }

  /**
   * Internal method to perform the actual loading.
   * @private
   * @returns {Promise<void>}
   */
  async _doLoadAll() {
    // Lazy-load tier1_gear.json
    const tier1Gear = await import("../items/tier1_gear.json", { with: { type: "json" } }).then(m => m.default);
    
    // Load tier1_gear.json
    for (const itemDef of tier1Gear) {
      if (itemDef && itemDef.id) {
        const item = new Item(itemDef);
        this.items.set(itemDef.id, item);
      }
    }

    console.log(`Loaded ${this.items.size} items`);
  }

  /**
   * Gets an item definition by ID.
   * @param {string} itemId - Item ID
   * @returns {Item | undefined} - Item definition
   */
  get(itemId) {
    return this.items.get(itemId);
  }

  /**
   * Gets all item definitions.
   * @returns {Item[]} - Array of all items
   */
  getAll() {
    return Array.from(this.items.values());
  }
}

// Export singleton instance
export const itemRegistry = new ItemRegistry();

