import BoxError from '../boxerror.js';
import eventlog from '../eventlog.js';
import validator from '../validator.js';
import { HttpError } from '@cloudron/connect-lastmile';
import { HttpSuccess } from '@cloudron/connect-lastmile';
import safe from 'safetydance';


async function get(req, res, next) {
    const [error, event] = await safe(eventlog.get(req.params.eventId));
    if (error) return next(BoxError.toHttpError(error));
    if (!event) return next(new HttpError(404, 'Eventlog not found'));

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

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'));

    if (req.query.actions && typeof req.query.actions !== 'string') return next(new HttpError(400, 'actions must be a comma separated string'));
    if (req.query.action && typeof req.query.action !== 'string') return next(new HttpError(400, 'action must be a string'));
    if (req.query.search && typeof req.query.search !== 'string') return next(new HttpError(400, 'search must be a string'));

    if (req.query.from) {
        if (typeof req.query.from !== 'string') return next(new HttpError(400, 'from must be an ISO 8601 datetime string'));
        if (!validator.isIsoDate(req.query.from)) return next(new HttpError(400, 'from must be a valid ISO 8601 datetime string'));
    }

    if (req.query.to) {
        if (typeof req.query.to !== 'string') return next(new HttpError(400, 'to must be an ISO 8601 datetime string'));
        if (!validator.isIsoDate(req.query.to)) return next(new HttpError(400, 'to must be a valid ISO 8601 datetime string'));
    }

    const actions = typeof req.query.actions === 'string' ? req.query.actions.split(',').map(function (s) { return s.trim(); }) : [];
    if (req.query.action) actions.push(req.query.action);

    if (req.query.to && !validator.isIsoDate(req.query.to)) return next(new HttpError(400, 'to must be a valid ISO 8601 datetime string'));

    const filter = {
        actions,
        search: req.query.search || null,
        from: req.query.from ? new Date(req.query.from) : null,
        to: req.query.to ? new Date(req.query.to) : null
    };

    const [error, eventlogs] = await safe(eventlog.listPaged(filter, page, perPage));
    if (error) return next(BoxError.toHttpError(error));

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

export default {
    get,
    list
};
