import {and, eq, sql} 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 {users} from "../../../../../database/schema/users.js";

export const updateSetting = 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 updated`);

        //get the username so we can update the correct field
        const user = await db.select().from(users).where(eq(users.user_id, user_id));
        try {
            //const settingID = await db.select().from(settings).where(eq(settings.name, data.module));

            const updateSetting = await db
            .update(settings)
            .set({value: data.value, upd_user: user[0].username, upd_date: sql`NOW()`})
            .where(eq(settings.name, data.name));
        } catch (error) {
            createLog("error", "lst", "server", "Error updating setting");
            throw new Error("Error updating 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");
    }
};
