/*
pass over a users uuid and return all modules they have permission too. 
in the login route we attach it to user under roles.
*/

import { eq } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { userRoles } from "../../../../../database/schema/userRoles.js";

export const roleCheck = async (user_id: string | undefined) => {
    if (!user_id) {
        throw Error("Missing user_id");
    }
    let returnRoles: any = [];
    // get the user roles by the user_id
    returnRoles = await db
        .select({
            user_id: userRoles.user_id,
            role_id: userRoles.role_id,
            module_id: userRoles.module_id,
            role: userRoles.role,
        })
        .from(userRoles)
        .where(eq(userRoles.user_id, user_id));

    if (returnRoles[0]?.role.includes("systemAdmin")) {
        const roles = await db
            .select({
                user_id: userRoles.user_id,
                role_id: userRoles.role_id,
                module_id: userRoles.module_id,
                role: userRoles.role,
            })
            .from(userRoles)
            .where(eq(userRoles.user_id, user_id));

        return roles;
    }

    return returnRoles;
};
