process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
import axios from "axios";
import { db } from "../../../../../database/dbclient.js";
import { settings } from "../../../../../database/schema/settings.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { createLog } from "../../../logger/logger.js";
import type { Settings } from "../../../../types/settings.js";

export let serverSettings: Settings[];
export const getSettings = async () => {
    const settingsType = process.env.LST_USE_GO;
    createLog(
        "info",
        "lst",
        "server",
        `Settings are being grabbed from: ${
            settingsType === "true" ? "Go backend" : "Localbackend"
        }`
    );

    const baseUrl = process.env.LST_BASE_URL;

    if (settingsType === "true") {
        const { data, error } = (await tryCatch(
            axios.get(`${baseUrl}/api/v1/settings`)
        )) as any;

        if (error) {
            createLog(
                "error",
                "lst",
                "server",
                "There was an error getting the settings"
            );
            throw new Error("There was an error getting the settings");
        }

        serverSettings = data.data.data;
    }

    if (settingsType !== "true") {
        try {
            serverSettings = (await db.select().from(settings)) as any;
            //.where(sql`${userRole} = ANY(roles)`);
        } catch (error) {
            createLog(
                "error",
                "lst",
                "server",
                "There was an error getting the settings"
            );
            throw new Error("There was an error getting the settings");
        }
    }

    return serverSettings;
};
