import assert from 'node:assert';
import BoxError from './boxerror.js';
import constants from './constants.js';
import logger from './logger.js';
import eventlog from './eventlog.js';
import oidcClients from './oidcclients.js';
import oidcServer from './oidcserver.js';
import settings from './settings.js';
import tokens from './tokens.js';
import users from './users.js';

const { log } = logger('user-directory');


async function getProfileConfig() {
    const value = await settings.getJson(settings.PROFILE_CONFIG_KEY);
    return value || { lockUserProfiles: false, mandatory2FA: false };
}

async function setProfileConfig(profileConfig, options, auditSource) {
    assert.strictEqual(typeof profileConfig, 'object');
    assert.strictEqual(typeof options, 'object');
    assert(auditSource && typeof auditSource === 'object');

    if (constants.DEMO) throw new BoxError(BoxError.BAD_STATE, 'Not allowed in demo mode');

    const oldConfig = await getProfileConfig();
    await settings.setJson(settings.PROFILE_CONFIG_KEY, profileConfig);

    await eventlog.add(eventlog.ACTION_USER_DIRECTORY_PROFILE_CONFIG_UPDATE, auditSource, { oldConfig, config: profileConfig });

    if (profileConfig.mandatory2FA && !oldConfig.mandatory2FA) {
        log('setProfileConfig: logging out non-2FA users to enforce 2FA');

        const allUsers = await users.list();

        for (const user of allUsers) {
            if (user.totpEnabled) continue;
            if (options.persistUserIdSessions === user.id) continue; // do not logout the API caller
            if (!user.username) continue; // if a user has no username set yet

            await tokens.delByUserIdAndType(user.id, oidcClients.ID_WEBADMIN);
            await oidcServer.revokeByUsername(user.username);
        }
    }
}

export default {
    getProfileConfig,
    setProfileConfig
};
