/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import {
  Construction,
  Days,
  Logger,
  StorageService,
  Time
} from "#general";
import { DclClient } from "./DclClient.js";
const logger = Logger.get("DclVendorInfoService");
class DclVendorInfoService {
  #construction;
  #storageManager;
  #storage;
  #vendorIndex = /* @__PURE__ */ new Map();
  #updateTimer;
  #closed = false;
  #options;
  #fetchPromise;
  constructor(environment, options = {}) {
    environment.root.set(DclVendorInfoService, this);
    this.#options = options;
    this.#construction = Construction(this, async () => {
      this.#storageManager = await environment.get(StorageService).open("vendors");
      this.#storage = this.#storageManager.createContext("info");
      await this.#loadVendors(this.#storage);
      await this.update();
      if (options.updateInterval !== null) {
        const updateInterval = options.updateInterval ?? Days.one;
        this.#updateTimer = Time.getPeriodicTimer(
          "DCL Vendor Info Update",
          updateInterval,
          () => this.update()
        ).start();
      }
    });
  }
  get construction() {
    return this.#construction;
  }
  /**
   * Get vendor information by vendor ID. Returns undefined if not found.
   */
  infoFor(vendorId) {
    this.construction.assert();
    return this.#vendorIndex.get(vendorId);
  }
  /**
   * Get all vendor information as a map indexed by vendor ID.
   */
  get vendors() {
    this.construction.assert();
    return this.#vendorIndex;
  }
  /**
   * Update vendor information from DCL.
   */
  async update() {
    if (this.#closed || !this.#storage) {
      return;
    }
    if (this.#fetchPromise !== void 0) {
      await this.#fetchPromise;
      return;
    }
    try {
      this.#fetchPromise = this.#fetchVendorsFromDcl(this.#storage).finally(() => {
        this.#fetchPromise = void 0;
      });
      await this.#fetchPromise;
    } catch (error) {
      logger.info("Error updating vendor information", error);
    }
  }
  /**
   * Load vendor information from storage.
   */
  async #loadVendors(storage) {
    const storedVendors = await storage.get("vendors", []);
    for (const vendor of storedVendors) {
      this.#vendorIndex.set(vendor.vendorId, vendor);
    }
    if (storedVendors.length > 0) {
      logger.info(`Loaded ${this.#vendorIndex.size} vendors from storage`);
    }
  }
  /**
   * Fetch vendor information from DCL and store it.
   */
  async #fetchVendorsFromDcl(storage) {
    logger.info("Fetching vendor information from DCL...");
    const dclClient = new DclClient(true);
    const vendors = await dclClient.fetchAllVendors(this.#options);
    logger.info(`Fetched ${vendors.length} vendors from DCL`);
    const hardcodedVendors = [
      ...[65521, 65522, 65523, 65524].map((vendorID) => ({
        vendorID,
        vendorName: "Test Vendor",
        companyLegalName: "Test Vendor Inc.",
        companyPreferredName: "Test Vendor",
        vendorLandingPageURL: "https://test.example.com",
        creator: "System"
      })),
      {
        vendorID: 4939,
        vendorName: "Nabu Casa",
        companyLegalName: "Nabu Casa, Inc.",
        companyPreferredName: "Nabu Casa",
        vendorLandingPageURL: "https://www.nabucasa.com",
        creator: "System"
      }
    ];
    for (const hardcoded of hardcodedVendors) {
      if (!vendors.find((v) => v.vendorID === hardcoded.vendorID)) {
        vendors.push(hardcoded);
      }
    }
    const vendorsToStore = [];
    for (const vendor of vendors) {
      const normalizedVendor = this.#normalizeDclVendor(vendor);
      this.#vendorIndex.set(normalizedVendor.vendorId, normalizedVendor);
      vendorsToStore.push(normalizedVendor);
    }
    await storage.set("vendors", vendorsToStore);
    logger.info(`Stored ${this.#vendorIndex.size} vendors`);
  }
  /**
   * Normalize DCL vendor format to internal format.
   */
  #normalizeDclVendor(dclVendor) {
    return {
      vendorId: dclVendor.vendorID,
      vendorName: dclVendor.vendorName,
      companyLegalName: dclVendor.companyLegalName,
      companyPreferredName: dclVendor.companyPreferredName,
      vendorLandingPageUrl: dclVendor.vendorLandingPageURL,
      creator: dclVendor.creator
    };
  }
  /**
   * Close the service and stop periodic updates.
   */
  async close() {
    if (this.#closed) return;
    this.#closed = true;
    await this.#fetchPromise;
    if (this.#updateTimer) {
      this.#updateTimer.stop();
      this.#updateTimer = void 0;
    }
    await this.#storageManager?.close();
  }
}
export {
  DclVendorInfoService
};
//# sourceMappingURL=DclVendorInfoService.js.map
