export class FactionActionRegistry {
    static #actions = new Map();

    static register(definition = {}) {
        const id = String(definition.id || "").trim();
        if (!id) throw new Error("Faction actions require an id.");
        if (typeof definition.onSelect !== "function") {
            throw new Error(`Faction action "${id}" requires an onSelect handler.`);
        }
        const action = {
            id,
            moduleId: String(definition.moduleId || "").trim(),
            label: definition.label,
            icon: String(definition.icon || "fas fa-puzzle-piece").trim(),
            order: Number(definition.order) || 0,
            matches: typeof definition.matches === "function" ? definition.matches : () => true,
            onSelect: definition.onSelect
        };
        this.#actions.set(id, action);
        Hooks.callAll("augurNexusFactionActionsChanged", { reason: "register", action: { id, moduleId: action.moduleId } });
        return { id, moduleId: action.moduleId };
    }

    static listFor(faction, { onChanged = null } = {}) {
        if (!faction) return [];
        const context = { faction, user: game.user };
        return [...this.#actions.values()]
            .filter(action => {
                try { return action.matches(context) !== false; }
                catch (error) {
                    console.error(`Augur Nexus | Faction action "${action.id}" match failed`, error);
                    return false;
                }
            })
            .sort((left, right) => left.order - right.order || left.id.localeCompare(right.id))
            .map(action => ({
                id: action.id,
                label: typeof action.label === "function" ? String(action.label(context) || action.id) : String(action.label || action.id),
                icon: action.icon,
                onSelect: () => action.onSelect({ ...context, onChanged })
            }));
    }
}
