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


async function load(req, res, next) {
    assert.strictEqual(typeof req.params.id, 'string');

    const [error, result] = await safe(backups.get(req.params.id));
    if (error) return next(BoxError.toHttpError(error));
    if (!result) return next(new HttpError(404, 'Backup not found'));

    req.resources.backup = result;

    next();
}

async function get(req, res, next) {
    assert.strictEqual(typeof req.params.id, 'string');

    next(new HttpSuccess(200,  backups.removePrivateFields(req.resources.backup)));
}

async function list(req, res, next) {
    const page = typeof req.query.page === 'string' ? parseInt(req.query.page) : 1;
    if (!page || page < 0) return next(new HttpError(400, 'page query param has to be a postive number'));

    const perPage = typeof req.query.per_page === 'string'? parseInt(req.query.per_page) : 25;
    if (!perPage || perPage < 0) return next(new HttpError(400, 'per_page query param has to be a postive number'));

    const [error, result] = await safe(backups.listByIdentifierAndStatePaged(backups.BACKUP_IDENTIFIER_BOX, backups.BACKUP_STATE_NORMAL, page, perPage));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(200, { backups: result.map(backups.removePrivateFields) }));
}

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

    const { label, preserveSecs } = req.body;
    if (typeof label !== 'string') return next(new HttpError(400, 'label must be a string'));
    if (typeof preserveSecs !== 'number') return next(new HttpError(400, 'preserveSecs must be a number'));

    const [error] = await safe(backups.update(req.resources.backup, { label, preserveSecs }));
    if (error) return next(BoxError.toHttpError(error));

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

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

    const [error, taskId] = await safe(backups.startIntegrityCheck(req.resources.backup, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

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

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

    const [error] = await safe(backups.stopIntegrityCheck(req.resources.backup, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

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

export default {
    load,

    list,
    get,
    update,

    startIntegrityCheck,
    stopIntegrityCheck
};
