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


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

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

    req.resources.user = result; // this is not req.user because req.user is already the authenticated user

    next();
}

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

    if (typeof req.body.email !== 'string') return next(new HttpError(400, 'email must be string'));
    if ('username' in req.body && typeof req.body.username !== 'string') return next(new HttpError(400, 'username must be string'));
    if ('fallbackEmail' in req.body && typeof req.body.fallbackEmail !== 'string') return next(new HttpError(400, 'fallbackEmail must be string'));
    if ('displayName' in req.body && typeof req.body.displayName !== 'string') return next(new HttpError(400, 'displayName must be string'));
    if ('password' in req.body && typeof req.body.password !== 'string') return next(new HttpError(400, 'password must be string'));
    if ('role' in req.body) {
        if (typeof req.body.role !== 'string') return next(new HttpError(400, 'role must be string'));
        if (users.compareRoles(req.user.role, req.body.role) < 0) return next(new HttpError(403, `role '${req.body.role}' is required but you are only '${req.user.role}'`));
    }

    const password = req.body.password || null;
    const email = req.body.email;
    const username = 'username' in req.body ? req.body.username : null;
    const displayName = req.body.displayName || '';
    const fallbackEmail = req.body.fallbackEmail || '';

    const [error, id] = await safe(users.add(email, { username, password, displayName, fallbackEmail, invitor: req.user, role: req.body.role || users.ROLE_USER }, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(201, { id }));
}

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

    if (typeof req.body.role !== 'string') return next(new HttpError(400, 'role must be a string'));
    if (req.user.id === req.resources.user.id) return next(new HttpError(409, 'Cannot set role flag on self'));

    if (users.compareRoles(req.user.role, req.body.role) < 0) return next(new HttpError(403, `role '${req.body.role}' is required but you are only '${req.user.role}'`));
    if (users.compareRoles(req.user.role, req.resources.user.role) < 0) return next(new HttpError(403, `role '${req.resources.user.role}' is required but you are only '${req.user.role}'`));

    const [error] = await safe(users.update(req.resources.user, { role: req.body.role }, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(204));
}

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

    if (typeof req.body.active !== 'boolean') return next(new HttpError(400, 'active must be a boolean'));
    if (req.user.id === req.resources.user.id) return next(new HttpError(409, 'Cannot set active flag on self'));

    if (users.compareRoles(req.user.role, req.resources.user.role) < 0) return next(new HttpError(403, `role '${req.resources.user.role}' is required but you are only '${req.user.role}'`));

    const [error] = await safe(users.update(req.resources.user, { active: req.body.active }, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(204));
}

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

    const [avatarError, avatar] = await safe(users.getAvatar(req.resources.user));
    if (avatarError) return next(BoxError.toHttpError(avatarError));
    if (!avatar) return next(new HttpError(404, 'no avatar'));

    res.set('Content-Type', 'image/png');
    res.status(200).send(avatar);
}

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

    const avatar = safe.fs.readFileSync(req.files.avatar.path);
    safe.fs.unlinkSync(req.files.avatar.path);
    if (!avatar) return next(BoxError.toHttpError(new BoxError(BoxError.FS_ERROR, safe.error.message)));

    const [error] = await safe(users.setAvatar(req.resources.user, avatar));
    if (error) return next(BoxError.toHttpError(error));

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

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

    const [error] = await safe(users.setAvatar(req.resources.user, null));
    if (error) return next(BoxError.toHttpError(error));

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

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

    if ('username' in req.body && typeof req.body.username !== 'string') return next(new HttpError(400, 'username must be string')); // when profile are locked, admin can set username
    if ('email' in req.body && typeof req.body.email !== 'string') return next(new HttpError(400, 'email must be string'));
    if ('fallbackEmail' in req.body && typeof req.body.fallbackEmail !== 'string') return next(new HttpError(400, 'fallbackEmail must be string'));
    if ('displayName' in req.body && typeof req.body.displayName !== 'string') return next(new HttpError(400, 'displayName must be string'));

    if (users.compareRoles(req.user.role, req.resources.user.role) < 0) return next(new HttpError(403, `role '${req.resources.user.role}' is required but you are only '${req.user.role}'`));

    const data = _.pick(req.body, ['username', 'email', 'fallbackEmail', 'displayName']);
    const [error] = await safe(users.updateProfile(req.resources.user, data, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(204));
}

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.search && typeof req.query.search !== 'string') return next(new HttpError(400, 'search must be a string'));

    const active = typeof req.query.active === 'string' ? ((req.query.active === '1' || req.query.active === 'true') ? true : false) : null;

    const [error, results] = await safe(users.listPaged(req.query.search || null, active, page, perPage));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(200, { users: results.map(users.removePrivateFields) }));
}

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

    next(new HttpSuccess(200, users.removePrivateFields(req.resources.user)));
}

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

    if (req.user.id === req.resources.user.id) return next(new HttpError(409, 'Not allowed to remove yourself.'));
    if (users.compareRoles(req.user.role, req.resources.user.role) < 0) return next(new HttpError(403, `role '${req.resources.user.role}' is required but user has only '${req.user.role}'`));

    const [error] = await safe(users.del(req.resources.user, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(204));
}

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

    if (typeof req.body.password !== 'string') return next(new HttpError(400, 'API call requires user password'));

    const [error] = await safe(users.verifyWithId(req.user.id, req.body.password, users.AP_WEBADMIN, { skipTotpCheck: true }));
    if (error) return next(BoxError.toHttpError(error));

    req.body.password = '<redacted>'; // this will prevent logs from displaying plain text password

    next();
}

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

    if (users.compareRoles(req.user.role, req.resources.user.role) < 0) return next(new HttpError(403, `role '${req.resources.user.role}' is required but user has only '${req.user.role}'`));

    const [error] = await safe(users.disableTotp(req.resources.user, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

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

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

    if (!Array.isArray(req.body.groupIds)) return next(new HttpError(400, 'API call requires a groups array.'));
    if (req.body.groupIds.some((gid) => typeof gid !== 'string')) return next(new HttpError(400, 'groupIds array must contain strings'));
    if (users.compareRoles(req.user.role, req.resources.user.role) < 0) return next(new HttpError(403, `role '${req.resources.user.role}' is required but user has only '${req.user.role}'`));

    const [error] = await safe(groups.setLocalMembership(req.resources.user, req.body.groupIds, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(204));
}

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

    if (typeof req.body.password !== 'string' || !req.body.password) return next(new HttpError(400, 'password must be non-empty string'));
    if ('expiresAt' in req.body && typeof req.body.expiresAt !== 'number') return next(new HttpError(400, 'expiresAt must be a number'));
    if (users.compareRoles(req.user.role, req.resources.user.role) < 0) return next(new HttpError(403, `role '${req.resources.user.role}' is required but user has only '${req.user.role}'`));

    const [error] = await safe(users.setGhost(req.resources.user, req.body.password, req.body.expiresAt || 0));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(204));
}

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

    if (typeof req.body.password !== 'string') return next(new HttpError(400, 'password must be a string'));
    if (users.compareRoles(req.user.role, req.resources.user.role) < 0) return next(new HttpError(403, `role '${req.resources.user.role}' is required but user has only '${req.user.role}'`));

    const [error] = await safe(users.setPassword(req.resources.user, req.body.password, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(204));
}

// This will always return a reset link, if none is set or expired a new one will be created
async function getPasswordResetLink(req, res, next) {
    assert.strictEqual(typeof req.resources.user, 'object');

    if (users.compareRoles(req.user.role, req.resources.user.role) < 0) return next(new HttpError(403, `role '${req.resources.user.role}' is required but user has only '${req.user.role}'`));

    const [error, passwordResetLink] = await safe(users.getPasswordResetLink(req.resources.user, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

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

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

    if (!req.body.email || typeof req.body.email !== 'string') return next(new HttpError(400, 'email must be a non-empty string'));
    if (users.compareRoles(req.user.role, req.resources.user.role) < 0) return next(new HttpError(403, `role '${req.resources.user.role}' is required but user has only '${req.user.role}'`));

    const [error] = await safe(users.sendPasswordResetEmail(req.resources.user, req.body.email, AuditSource.fromRequest(req)));
    if (error)  return next(BoxError.toHttpError(error));

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

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

    if (users.compareRoles(req.user.role, req.resources.user.role) < 0) return next(new HttpError(403, `role '${req.resources.user.role}' is required but user has only '${req.user.role}'`));

    const [error, inviteLink] = await safe(users.getInviteLink(req.resources.user, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

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

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

    if (!req.body.email || typeof req.body.email !== 'string') return next(new HttpError(400, 'email must be a non-empty string'));
    if (users.compareRoles(req.user.role, req.resources.user.role) < 0) return next(new HttpError(403, `role '${req.resources.user.role}' is required but user has only '${req.user.role}'`));

    const [error] = await safe(users.sendInviteEmail(req.resources.user, req.body.email, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

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

export default {
    get,
    list,
    add,
    del,

    setRole,
    setActive,
    getAvatar,
    setAvatar,
    unsetAvatar,
    updateProfile,

    setPassword,
    verifyPassword,
    setLocalGroups,
    setGhost,

    getPasswordResetLink,
    sendPasswordResetEmail,

    getInviteLink,
    sendInviteEmail,

    disableTotp,

    load
};
