// ==========================================
// Switchboard Core — SDK: Storage Module
// ==========================================
// Namespaced localStorage wrapper.
//
// Factory: createStorage()
// ==========================================

/**
 * Create the storage module.
 *
 * @returns {object} storage — { local(namespace) }
 */
export function createStorage() {
    return {
        /**
         * Scoped localStorage wrapper.
         * @param {string} ns — namespace (e.g. package id)
         * @returns {object} — { get, set, remove, keys, clear }
         */
        local(ns) {
            const prefix = 'sw::' + ns + '::';

            return {
                get(key) {
                    const raw = localStorage.getItem(prefix + key);
                    if (raw === null) return null;
                    try { return JSON.parse(raw); }
                    catch { return raw; }
                },

                set(key, val) {
                    localStorage.setItem(prefix + key, JSON.stringify(val));
                },

                remove(key) {
                    localStorage.removeItem(prefix + key);
                },

                keys() {
                    const out = [];
                    for (let i = 0; i < localStorage.length; i++) {
                        const k = localStorage.key(i);
                        if (k.startsWith(prefix)) out.push(k.slice(prefix.length));
                    }
                    return out;
                },

                clear() {
                    const toRemove = [];
                    for (let i = 0; i < localStorage.length; i++) {
                        const k = localStorage.key(i);
                        if (k.startsWith(prefix)) toRemove.push(k);
                    }
                    toRemove.forEach(k => localStorage.removeItem(k));
                },
            };
        },
    };
}
