import { getModules } from "@open-mercato/shared/lib/i18n/server";
let widgetEntriesPromise = null;
function invalidateWidgetCache() {
  widgetEntriesPromise = null;
  widgetCache.clear();
}
async function loadWidgetEntries() {
  if (!widgetEntriesPromise) {
    widgetEntriesPromise = Promise.resolve().then(() => {
      const list = getModules();
      return list.flatMap((mod) => {
        const entries = mod.dashboardWidgets ?? [];
        return entries.map((entry) => ({
          ...entry,
          moduleId: mod.id
        }));
      });
    });
  }
  return widgetEntriesPromise;
}
const widgetCache = /* @__PURE__ */ new Map();
function ensureValidWidgetModule(mod, key, moduleId) {
  if (!mod || typeof mod !== "object") {
    throw new Error(`Invalid dashboard widget module "${key}" from "${moduleId}" (expected object export)`);
  }
  const widget = mod.default ?? mod;
  if (!widget || typeof widget !== "object") {
    throw new Error(`Invalid dashboard widget export "${key}" from "${moduleId}" (missing default export)`);
  }
  if (!widget.metadata || typeof widget.metadata !== "object") {
    throw new Error(`Dashboard widget "${key}" from "${moduleId}" is missing metadata`);
  }
  const { metadata } = widget;
  if (typeof metadata.id !== "string" || metadata.id.length === 0) {
    throw new Error(`Dashboard widget "${key}" from "${moduleId}" metadata.id must be a non-empty string`);
  }
  if (typeof metadata.title !== "string" || metadata.title.length === 0) {
    throw new Error(`Dashboard widget "${metadata.id}" from "${moduleId}" must have a title`);
  }
  return {
    ...widget,
    metadata
  };
}
async function loadEntry(entry) {
  if (!widgetCache.has(entry.key)) {
    const promise = entry.loader().then((mod) => ensureValidWidgetModule(mod, entry.key, entry.moduleId));
    widgetCache.set(entry.key, promise);
  }
  return widgetCache.get(entry.key);
}
async function loadAllWidgets() {
  const widgetEntries = await loadWidgetEntries();
  const loaded = await Promise.all(widgetEntries.map(async (entry) => {
    const widget = await loadEntry(entry);
    return { ...widget, moduleId: entry.moduleId, key: entry.key };
  }));
  const byId = /* @__PURE__ */ new Map();
  for (const widget of loaded) {
    if (!byId.has(widget.metadata.id)) {
      byId.set(widget.metadata.id, widget);
    }
  }
  return Array.from(byId.values());
}
async function loadWidgetById(widgetId) {
  const widgetEntries = await loadWidgetEntries();
  for (const entry of widgetEntries) {
    const widget = await loadEntry(entry);
    if (widget.metadata.id === widgetId) {
      return { ...widget, moduleId: entry.moduleId, key: entry.key };
    }
  }
  return null;
}
export {
  invalidateWidgetCache,
  loadAllWidgets,
  loadWidgetById
};
//# sourceMappingURL=widgets.js.map
