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


async function sync(req, res, next) {
    const [error, taskId] = await safe(externalLdap.startSyncer());
    if (error) return next(new HttpError(500, error.message));

    next(new HttpSuccess(202, { taskId }));
}

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

    next(new HttpSuccess(200, externalLdap.removePrivateFields(config)));
}

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

    if (!req.body.provider || typeof req.body.provider !== 'string') return next(new HttpError(400, 'provider must be a string'));
    if ('url' in req.body && typeof req.body.url !== 'string') return next(new HttpError(400, 'url must be a string'));
    if ('baseDn' in req.body && typeof req.body.baseDn !== 'string') return next(new HttpError(400, 'baseDn must be a string'));
    if ('usernameField' in req.body && typeof req.body.usernameField !== 'string') return next(new HttpError(400, 'usernameField must be a string'));
    if ('filter' in req.body && typeof req.body.filter !== 'string') return next(new HttpError(400, 'filter must be a string'));
    if ('groupBaseDn' in req.body && typeof req.body.groupBaseDn !== 'string') return next(new HttpError(400, 'groupBaseDn must be a string'));
    if ('bindDn' in req.body && typeof req.body.bindDn !== 'string') return next(new HttpError(400, 'bindDn must be a non empty string'));
    if ('bindPassword' in req.body && typeof req.body.bindPassword !== 'string') return next(new HttpError(400, 'bindPassword must be a string'));

    req.clearTimeout(); // remove ldap server can take a bit to respond

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

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

export default {
    getConfig,
    setConfig,
    sync
};
