
import {
    Group,
    User
} from "../../../../lib/database/connect.mjs";


export const get = async function (request, response) {
    if (request.getAuthState() != 'authenticated') {
        response.set('HX-Redirect', '/login').status(401).end();
        return;
    }

    const dbUser = await User.findByPk(request.params.userid);

    if (!dbUser) {
        response.status(404).end('User not found');
        return;
    }

    const userGroups = await (async () => {
        if (!dbUser.othergroups || dbUser.othergroups.length == 0) {
            return [];
        } else {
            return dbUser.othergroups.split(',').map(gid => parseInt(gid));
        }
    })();

    const groupList = (await Group.findAll()).map((dbGroup) => {
        return {
            id: dbGroup.id,
            gidnumber: dbGroup.gidnumber,
            name: dbGroup.name,
            isPrimaryGroup: dbUser.primarygroup == dbGroup.gidnumber,
            isOtherGroup: userGroups.includes(dbGroup.gidnumber)
        };
    });

    console.log(groupList);

    response.render(`views/htmx/admin/editUser.njk`, {
        user: {
            id: dbUser.id,
            username: dbUser.name,
            uidnumber: dbUser.uidnumber,
            firstName: dbUser.givenname,
            lastName: dbUser.sn,
            mail: dbUser.mail,
            disabled: dbUser.disabled,
        },
        groupList: groupList
    });
}