import {and, eq} from "drizzle-orm";
import {db} from "../../../../../database/dbclient.js";
import {settings} from "../../../../../database/schema/settings.js";
import {createLog} from "../../../logger/logger.js";
import {userRoles} from "../../../../../database/schema/userRoles.js";
import {modules} from "../../../../../database/schema/modules.js";

export const addSetting = async (data: any, user_id: string) => {
    createLog("info", "lst", "server", "Adding a new setting");

    // make sure the user is a system admin before moving forward
    const sysAdmin = await db
    .select()
    .from(userRoles)
    .where(and(eq(userRoles.user_id, user_id), eq(userRoles.role, "systemAdmin")));

    if (sysAdmin) {
        createLog("info", "lst", "server", `Setting ${data.name} is being added`);
        try {
            const moduleId = await db.select().from(modules).where(eq(modules.name, data.module));

            // filter out the module and add in the module id
            //delete data.module;

            //data.moduleName = moduleId[0].module_id;
            // console.log(data);
            const createSetting = await db.insert(settings).values(data);
        } catch (error) {
            createLog("error", "lst", "server", "Error adding setting");
            throw new Error("Error Adding Setting");
        }
    } else {
        createLog("error", "lst", "server", "This user cannot add new roles");
        throw new Error("The user trying to add a setting dose not have the correct permissions");
    }
};
