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

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

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

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

    if (typeof req.body.schedule !== 'string') return next(new HttpError(400, 'schedule is required'));
    if (typeof req.body.policy !== 'string') return next(new HttpError(400, 'policy is required'));

    const [error] = await safe(updater.setAutoupdateConfig(req.body));
    if (error) return next(BoxError.toHttpError(error));

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

async function updateBox(req, res, next) {
    if ('skipBackup' in req.body && typeof req.body.skipBackup !== 'boolean') return next(new HttpError(400, 'skipBackup must be a boolean'));

    // this only initiates the update, progress can be checked via the progress route
    const [error, taskId] = await safe(updater.startBoxUpdateTask(req.body, AuditSource.fromRequest(req)));
    if (error && error.reason === BoxError.NOT_FOUND) return next(new HttpError(422, error.message));
    if (error && error.reason === BoxError.BAD_STATE) return next(new HttpError(409, error.message));
    if (error) return next(new HttpError(500, error));

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

async function getBoxUpdate(req, res, next) {
    const [error, boxUpdateInfo] = await safe(updater.getBoxUpdate());
    if (error) return next(new HttpError(500, error));
    next(new HttpSuccess(200, { update: boxUpdateInfo }));
}

async function checkBoxUpdate(req, res, next) {
    // it can take a while sometimes to get all the app updates one by one
    req.clearTimeout();

    const [error, result ] = await safe(updater.checkBoxUpdate({ stableOnly: false }));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(200, { update: result }));
}

export default {
    getAutoupdateConfig,
    setAutoupdateConfig,

    getBoxUpdate,
    checkBoxUpdate,

    updateBox,
};
