export class SettlementDossierProviderRegistry {
    static #providers = new Map();

    static register(definition = {}) {
        const id = String(definition.id || "").trim();
        if (!id || typeof definition.isAvailable !== "function") {
            throw new Error("Settlement dossier providers require an id and isAvailable function.");
        }
        const provider = {
            id,
            moduleId: String(definition.moduleId || "").trim(),
            priority: Number(definition.priority || 0),
            isAvailable: definition.isAvailable,
            prepare: typeof definition.prepare === "function" ? definition.prepare : null,
            openEstablishment: definition.openEstablishment,
            createEstablishment: definition.createEstablishment,
            recreateMarketplace: definition.recreateMarketplace,
            openTrade: definition.openTrade,
            openTradeGood: definition.openTradeGood,
            changeTradingCenter: definition.changeTradingCenter
        };
        this.#providers.set(id, provider);
        Hooks.callAll("augurNexusSettlementProvidersChanged", { id, moduleId: provider.moduleId });
        return { id, moduleId: provider.moduleId, priority: provider.priority };
    }

    static getFor(entity = {}) {
        return [...this.#providers.values()]
            .filter(provider => {
                try { return provider.isAvailable(entity) !== false; }
                catch (error) {
                    console.warn(`Augur: Nexus | Settlement provider ${provider.id} availability failed.`, error);
                    return false;
                }
            })
            .sort((left, right) => right.priority - left.priority)[0] || null;
    }
}
