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


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

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

    next(new HttpSuccess(200, appPasswords.removePrivateFields(result)));
}

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 (typeof req.body.identifier !== 'string') return next(new HttpError(400, 'identifier must be string'));
    if (req.body.expiresAt !== null && (typeof req.body.expiresAt !== 'string' || isNaN(new Date(req.body.expiresAt).getTime()))) return next(new HttpError(400, 'expiresAt must be null or a valid date string'));

    const [error, result] = await safe(appPasswords.add(req.user.id, req.body.identifier, req.body.name, req.body.expiresAt));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(201, { id: result.id, password: result.password }));
}

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

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

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

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

    // TODO: verify userId owns the id ?
    const [error] = await safe(appPasswords.del(req.params.id));
    if (error) return next(BoxError.toHttpError(error));

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

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