import { db } from "../../../../../database/dbclient.js";
import { userRoles } from "../../../../../database/schema/userRoles.js";
import { users } from "../../../../../database/schema/users.js";
import { returnRes } from "../../../../globalUtils/routeDefs/returnRes.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { createLog } from "../../../logger/logger.js";

export const getAllUsers = async () => {
    /**
     * returns all users that are in lst
     */
    createLog("info", "apiAuthedRoute", "auth", "Get all users");

    // get all users
    const { data, error } = await tryCatch(db.select().from(users));

    // add there modules they are in
    const { data: m, error: em } = await tryCatch(db.select().from(userRoles));

    const user: any = data;
    const userData = user.map((i: any) => {
        // module in
        const module = m?.filter((x: any) => x.user_id === i.user_id);

        if (module) {
            return { ...i, moduleRoles: module };
        } else {
            return;
        }
    });

    if (error) {
        returnRes(
            false,
            "auth",
            "auth",
            "There was an error getting users",
            "error",
            new Error("No user exists.")
        );
    }

    //returnRes(true, "All users.", data);
    return { success: true, message: "All users", data: userData };
};
