import { ShopStore } from "./ShopStore.js";

export class ShopEditorRegistry {
    static #handlers = new Map();

    static register(definition = {}) {
        const id = String(definition.id || "").trim();
        if (!id || typeof definition.matches !== "function" || typeof definition.open !== "function") {
            throw new Error("Shop editor handlers require an id, matches function, and open function.");
        }
        const handler = {
            id,
            moduleId: String(definition.moduleId || "").trim(),
            priority: Number(definition.priority) || 0,
            matches: definition.matches,
            open: definition.open
        };
        this.#handlers.set(id, handler);
        Hooks.callAll("augurNexusShopEditorsChanged", { reason: "register", id, moduleId: handler.moduleId });
        return { id, moduleId: handler.moduleId, priority: handler.priority };
    }

    static async open(options = {}) {
        const shop = options.shopId ? ShopStore.getShop(options.shopId) : null;
        const context = { ...options, shop };
        const handlers = [...this.#handlers.values()].sort((a, b) => b.priority - a.priority);
        for (const handler of handlers) {
            if (await handler.matches(context)) return handler.open(context);
        }
        const { ShopEditorApplication } = await import("../applications/ShopEditorApplication.js");
        return ShopEditorApplication.show(options);
    }
}
