import appstore from '../appstore.js';
import assert from 'node:assert';
import BoxError from '../boxerror.js';
import { HttpSuccess } from '@cloudron/connect-lastmile';
import safe from 'safetydance';
import users from '../users.js';
import _ from '../underscore.js';


async function getApps(req, res, next) {
    const [error, apps] = await safe(appstore.getApps());
    if (error) return next(BoxError.toHttpError(error));

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

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

    const [error, app] = await safe(appstore.getApp(req.params.appstoreId));
    if (error) return next(BoxError.toHttpError(error));

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

async function getAppVersion(req, res, next) {
    assert.strictEqual(typeof req.params.appstoreId, 'string');
    assert.strictEqual(typeof req.params.versionId, 'string');

    const [error, result] = await safe(appstore.getAppVersion(req.params.appstoreId, req.params.versionId));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(200, result));  // { id, creationDate, publishState, manifest, iconUrl }
}

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

    const [registerError] = await safe(appstore.unlinkAccount());
    if (registerError) return next(BoxError.toHttpError(registerError));

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

async function getSubscription(req, res, next) {
    const [error, result] = await safe(appstore.getSubscription());
    if (error) return next(BoxError.toHttpError(error));

    // non-owners only get a stripped down version
    if (users.compareRoles(req.user.role, users.ROLE_OWNER) < 0) next(new HttpSuccess(200, _.pick(result, ['plan', 'status'])));
    else next(new HttpSuccess(200, result)); // { email, cloudronId, cloudronCreatedAt, plan, current_period_end, canceled_at, cancel_at, status, features }
}

export default {
    getApps,
    getApp,
    getAppVersion,

    unlinkAccount,
    getSubscription
};
