/**
 * modules/fileSystem/biometricUnlock.js — Desbloqueo por huella para carpetas protegidas (TTL en memoria).
 */
(function (g) {
    g.modules = g.modules || {};
    g.modules.fileSystem = g.modules.fileSystem || {};

    var TTL_MS = 5 * 60 * 1000;
    var unlockedUntil = Object.create(null);

    function keyOf(bucket, relPath) {
        return g.modules.fileSystem.folderPermissions.makeKey(bucket, relPath);
    }

    function isUnlocked(bucket, relPath) {
        var k = keyOf(bucket, relPath);
        var t = unlockedUntil[k];
        return typeof t === 'number' && t > Date.now();
    }

    function markUnlocked(bucket, relPath) {
        unlockedUntil[keyOf(bucket, relPath)] = Date.now() + TTL_MS;
    }

    g.modules.fileSystem.biometricUnlock = {
        TTL_MS: TTL_MS,

        /** Llamado desde __gridAuthHooks.beforeEnterLocalFolder */
        ensureUnlocked: async function (ctx) {
            var bucket = ctx.bucket || 'files';
            var relPath = g.modules.fileSystem.folderPermissions.normalizeRelPath(ctx.relPath || '');
            var fp = g.modules.fileSystem.folderPermissions;
            var entry = await fp.getEntry(bucket, relPath);
            if (!entry || !entry.requireBiometric) return true;
            if (isUnlocked(bucket, relPath)) return true;

            var sess = g.modules.core.authSession.getUser();
            if (!sess || !sess.id) {
                g.modules.ui.messages.alert(g.modules.ui.messages.text('permNeedLogin'));
                return false;
            }

            var store = g.modules.users.userStore;
            var user = await store.findById(sess.id);
            if (!user || !(user.webauthnCredentials && user.webauthnCredentials.length)) {
                g.modules.ui.messages.alert(g.modules.ui.messages.text('permNoBioRegistered'));
                return false;
            }

            try {
                await g.modules.auth.biometricLogin.authenticate(user);
                markUnlocked(bucket, relPath);
                return true;
            } catch (_) {
                g.modules.ui.messages.alert(g.modules.ui.messages.text('permBioFailed'));
                return false;
            }
        },

        /** Invalidar (opcional). */
        clearUnlock: function (bucket, relPath) {
            delete unlockedUntil[keyOf(bucket, relPath)];
        },
    };
})(typeof window !== 'undefined' ? window : this);
