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


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

    const [error, result] = await safe(tokens.get(req.params.id));
    if (error) return next(BoxError.toHttpError(error));
    if (!result) return next(new HttpError(404, 'Token not found'));
    if (result.identifier !== req.user.id) return next(new HttpError(403, 'User is not owner'));

    req.targetToken = result;

    next();
}

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

    const [error, result] = await safe(tokens.listByUserId(req.user.id));
    if (error) return next(BoxError.toHttpError(error));

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

function get(req, res, next) {
    assert.strictEqual(typeof req.user, 'object');
    assert.strictEqual(typeof req.targetToken, 'object');

    next(new HttpSuccess(200, req.targetToken));
}

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

    if (typeof req.body.name !== 'string') return next(new HttpError(400, 'name must be string'));
    if ('expiresAt' in req.body && typeof req.body.expiresAt !== 'number') return next(new HttpError(400, 'expiresAt must be number'));
    if ('scope' in req.body && typeof req.body.scope !== 'object') return next(new HttpError(400, 'scope must be an object'));
    // this is a string to allow comments
    if ('allowedIpRanges' in req.body && typeof req.body.allowedIpRanges !== 'string') return next(new HttpError(400, 'allowedIpRanges must be a string'));

    const expiresAt = req.body.expiresAt || (Date.now() + (100 * 365 * 24 * 60 * 60 * 1000)); // forever - 100 years TODO maybe we should allow 0 or -1 to make that explicit
    const scope = req.body.scope || null;
    const allowedIpRanges = req.body.allowedIpRanges || '';

    const [error, result] = await safe(tokens.add({ clientId: oidcClients.ID_SDK, identifier: req.user.id, expires: expiresAt, name: req.body.name, scope, allowedIpRanges }));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(201, result));
}

async function del(req, res, next) {
    assert.strictEqual(typeof req.user, 'object');
    assert.strictEqual(typeof req.targetToken, 'object');

    const [error] = await safe(tokens.del(req.targetToken.id));
    if (error) return next(BoxError.toHttpError(error));

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

export default {
    verifyOwnership,
    list,
    get,
    add,
    del
};
