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


async function getStatus(req, res, next) {
    const [error, status] = await safe(cloudron.getStatus());
    if (error) return next(BoxError.toHttpError(error));

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

async function listLanguages(req, res, next) {
    const [error, languages] = await safe(translations.listLanguages());
    if (error) return next(new BoxError.toHttpError(error));

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

async function getTimeZone(req, res, next) {
    const [error, timeZone] = await safe(cloudron.getTimeZone());
    if (error) return next(BoxError.toHttpError(error));

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

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

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

    const [error] = await safe(cloudron.setTimeZone(req.body.timeZone));
    if (error) return next(BoxError.toHttpError(error));

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

async function getLanguage(req, res, next) {
    const [error, language] = await safe(cloudron.getLanguage());
    if (error) return next(BoxError.toHttpError(error));

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

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

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

    const [error] = await safe(cloudron.setLanguage(req.body.language));
    if (error) return next(BoxError.toHttpError(error));

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

export default {
    getStatus,

    listLanguages,
    getLanguage,
    setLanguage,

    getTimeZone,
    setTimeZone
};
