import assert from 'node:assert';
import AuditSource from '../auditsource.js';
import BoxError from '../boxerror.js';
import directoryServer from '../directoryserver.js';
import { HttpError } from '@cloudron/connect-lastmile';
import { HttpSuccess } from '@cloudron/connect-lastmile';
import safe from 'safetydance';


async function getConfig(req, res, next) {
    const [error, config] = await safe(directoryServer.getConfig());
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(200, config));
}

async function setConfig(req, res, next) {
    assert.strictEqual(typeof req.body, 'object');

    if (typeof req.body.enabled !== 'boolean') return next(new HttpError(400, 'enabled must be a boolean'));

    // these can still be there when enabled=false so that the values are preserved
    if ('secret' in req.body && typeof req.body.secret !== 'string') return next(new HttpError(400, 'secret must be a string'));
    if ('allowlist' in req.body && typeof req.body.allowlist !== 'string') return next(new HttpError(400, 'allowlist must be a string'));

    const [error] = await safe(directoryServer.setConfig(req.body, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(200, {}));
}

export default {
    getConfig,
    setConfig,
};
