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

import {
    getConfig
} from "../../../../lib/config.mjs";


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

    const dbGroup = await Group.findByPk(request.params.groupid);
    const config = await getConfig();

    const userList = await User.findAll({
        attributes: [
            'id',
            'uidnumber',
            'name',
            'othergroups',
            'primarygroup'
        ]
    }).filter((user) => {
        // check if users primary group is the group being edited
        if (user.primarygroup == dbGroup.gidnumber) {
            return true;
        }
        // check if users other groups include the group being edited
        if (user.othergroups.split(',').map(gidnumber => parseInt(gidnumber)).includes(dbGroup.gidnumber)) {
            return true;
        }
        // else exclude user
        return false;
    }).map((user) => {
        return {
            id: user.id,
            name: user.name,
            uidnumber: user.uidnumber,
        };
    });

    response.render(`views/htmx/admin/editGroup.njk`, {
        group: {
            id: dbGroup.id,
            name: dbGroup.name,
            gidnumber: dbGroup.gidnumber,
        },
        ldap: {
            baseDN: config.ldap.baseDN,
        },
        userList: userList
    });
}