/*
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 { and, eq } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { userRoles } from "../../../../../database/schema/userRoles.js";
import { users } from "../../../../../database/schema/users.js";
import { modules } from "../../../../../database/schema/modules.js";
import { roles } from "../../../../../database/schema/roles.js";
import { setSysAdmin } from "./setSysAdmin.js";

export const setUserAccess = async (
    username: string,
    moduleName: string,
    roleName: string,
    override?: string
) => {
    // get the user roles by the user_id
    const user = await db
        .select()
        .from(users)
        .where(eq(users.username, username));
    const module = await db
        .select()
        .from(modules)
        .where(eq(modules.name, moduleName));

    if (
        process.env.SECRETOVERRIDECODE != override &&
        roleName === "systemAdmin"
    ) {
        return {
            success: false,
            message: "The override code provided is invalid.",
        };
    }

    const role = await db.select().from(roles).where(eq(roles.name, roleName));

    /**
     * For system admin we want to do a little more
     */

    if (roleName === "systemAdmin") {
        await setSysAdmin(user, roleName);
        return {
            success: true,
            message: `${username} has been granted access to ${moduleName} with the role ${roleName}`,
        };
    }
    //console.log(user, module, role);

    // set the user
    try {
        const userRole = await db
            .insert(userRoles)
            .values({
                user_id: user[0].user_id,
                role_id: role[0].role_id,
                module_id: module[0].module_id,
                role: roleName,
            })
            .onConflictDoUpdate({
                target: userRoles.user_id,
                set: { role_id: role[0].role_id, role: roleName },
            });
        //.returning({user: users.username, email: users.email});

        // return c.json({message: "User Registered", user}, 200);
        return {
            success: true,
            message: `${username} has been granted access to ${moduleName} with the role ${roleName}`,
        };
    } catch (error) {
        await changeRole(
            roleName,
            user[0].user_id,
            module[0].module_id,
            role[0].role_id
        );
        return {
            success: true,
            message: `${username} access on ${moduleName} has been changed to ${roleName}`,
        };
    }
};

const changeRole = async (
    role: any,
    userID: any,
    moduleID: any,
    roleID: any
) => {
    await db
        .delete(userRoles)
        .where(
            and(
                eq(userRoles.user_id, userID),
                eq(userRoles.module_id, moduleID)
            )
        );

    const userRole = await db.insert(userRoles).values({
        user_id: userID,
        role_id: roleID,
        module_id: moduleID,
        role: role,
    });
};
