// ==========================================
// Switchboard Core — SDK: Action Registry
// ==========================================
// Named actions that extensions expose for invocation.
//
// Factory: createActions(emitFn)
// ==========================================

/**
 * Create the action registry.
 *
 * @param {Function} emitFn — events.emit for notifications
 * @returns {object} actions
 */
export function createActions(emitFn) {
    /** @type {Map<string, {handler:Function, label?:string, icon?:string}>} */
    const _registry = new Map();

    return {
        /**
         * Register a named action.
         * @param {string} id — unique action id (e.g. 'tasks.create')
         * @param {object} def — { handler, label?, icon? }
         * @returns {Function} unregister
         */
        register(id, { handler, label, icon }) {
            _registry.set(id, { handler, label, icon });
            emitFn('action.registered', { id, label }, { localOnly: true });
            return () => this.unregister(id);
        },

        /**
         * Remove an action.
         */
        unregister(id) {
            if (_registry.delete(id)) {
                emitFn('action.unregistered', { id }, { localOnly: true });
            }
        },

        /**
         * Execute an action by id.
         * @param {string} id
         * @param {...any} args — passed to handler
         * @returns {Promise<any>}
         */
        async run(id, ...args) {
            const entry = _registry.get(id);
            if (!entry) throw new Error(`[sw.actions] Unknown action: ${id}`);
            const result = await entry.handler(...args);
            emitFn('action.executed', { id }, { localOnly: true });
            return result;
        },

        /**
         * List registered action metadata.
         * @returns {Array<{id:string, label?:string, icon?:string}>}
         */
        list() {
            return [..._registry.entries()].map(([id, { label, icon }]) => ({ id, label, icon }));
        },

        /**
         * Check if an action is registered.
         */
        has(id) {
            return _registry.has(id);
        },
    };
}
