/**
 * modules/users/userCRUD.js — Alta/listado/edición/eliminación de usuarios.
 */
(function (g) {
    g.modules = g.modules || {};
    g.modules.users = g.modules.users || {};

    var crypto = g.modules.core.crypto;
    var store = g.modules.users.userStore;

    g.modules.users.userCRUD = {
        list: function () {
            return store.getAll();
        },

        create: async function (payload) {
            var blob = await store.load();
            var isFirst = blob.users.length === 0;
            var email = String(payload.email || '').trim();
            if (!email) throw new Error('email_required');
            if (await store.findByEmail(email)) throw new Error('email_exists');

            var passwordSalt = crypto.randomSaltB64();
            var passwordHash = await crypto.hashSecret(payload.password || '', passwordSalt);
            var pinSalt = crypto.randomSaltB64();
            var pinHash = await crypto.hashSecret(String(payload.pin || ''), pinSalt);
            var patternSalt = crypto.randomSaltB64();
            var patternSeq = String(payload.patternSeq || '');
            var patternHash = await crypto.hashSecret(patternSeq, patternSalt);

            var recoveryCode = payload.recoveryCode || '';
            var recoverySalt = crypto.randomSaltB64();
            var recoveryHash = recoveryCode ? await crypto.hashSecret(recoveryCode, recoverySalt) : '';

            var user = {
                id: store.generateId(),
                email: email,
                phone: String(payload.phone || '').trim(),
                passwordSalt: passwordSalt,
                passwordHash: passwordHash,
                pinSalt: pinSalt,
                pinHash: pinHash,
                patternSalt: patternSalt,
                patternHash: patternHash,
                recoverySalt: recoverySalt,
                recoveryHash: recoveryHash,
                metadata: {
                    loginType: payload.loginType || 'password',
                },
                webauthnCredentials: Array.isArray(payload.webauthnCredentials) ? payload.webauthnCredentials : [],
                role: isFirst ? 'admin' : 'user',
                createdAt: new Date().toISOString(),
            };
            await store.upsert(user);
            return user;
        },

        update: async function (id, patch) {
            var u = await store.findById(id);
            if (!u) throw new Error('not_found');
            if (patch.email && patch.email !== u.email) {
                if (await store.findByEmail(patch.email)) throw new Error('email_exists');
                u.email = String(patch.email).trim();
            }
            if (patch.phone !== undefined) u.phone = String(patch.phone || '').trim();
            if (patch.metadata && patch.metadata.loginType) {
                u.metadata = u.metadata || {};
                u.metadata.loginType = patch.metadata.loginType;
            }
            await store.upsert(u);
            return u;
        },

        delete: async function (id) {
            await store.remove(id);
        },
    };
})(typeof window !== 'undefined' ? window : this);
