/**
 * modules/users/userStore.js — Caché en memoria + persistencia vía storageAdapter.
 */
(function (g) {
    g.modules = g.modules || {};
    g.modules.users = g.modules.users || {};

    var cache = null;

    function genId() {
        if (g.crypto && g.crypto.randomUUID) return g.crypto.randomUUID();
        return 'u_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2);
    }

    g.modules.users.userStore = {
        generateId: genId,

        load: async function () {
            var adapt = g.modules.core.storageAdapter;
            cache = await adapt.getUsersBlob();
            if (!cache || !Array.isArray(cache.users)) cache = { version: 1, users: [] };
            return cache;
        },

        save: async function () {
            if (!cache) await this.load();
            return g.modules.core.storageAdapter.saveUsersBlob(cache);
        },

        getAll: async function () {
            if (!cache) await this.load();
            return cache.users.slice();
        },

        findById: async function (id) {
            if (!cache) await this.load();
            return cache.users.find(function (u) {
                return u.id === id;
            }) || null;
        },

        findByEmail: async function (email) {
            var e = String(email || '').trim().toLowerCase();
            if (!cache) await this.load();
            return cache.users.find(function (u) {
                return String(u.email || '').toLowerCase() === e;
            }) || null;
        },

        findByPhone: async function (phone) {
            var p = String(phone || '').replace(/\s+/g, '');
            if (!cache) await this.load();
            return cache.users.find(function (u) {
                return String(u.phone || '').replace(/\s+/g, '') === p;
            }) || null;
        },

        upsert: async function (user) {
            if (!cache) await this.load();
            var idx = cache.users.findIndex(function (u) {
                return u.id === user.id;
            });
            if (idx >= 0) cache.users[idx] = user;
            else cache.users.push(user);
            await this.save();
            return user;
        },

        remove: async function (id) {
            if (!cache) await this.load();
            cache.users = cache.users.filter(function (u) {
                return u.id !== id;
            });
            await this.save();
        },
    };
})(typeof window !== 'undefined' ? window : this);
