/**
 * This is only used now to get the settings from the new server
 */

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

import axios from "axios";
import { Client } from "pg";
import { db } from "../../../../../database/dbclient.js";
import { settings } from "../../../../../database/schema/settings.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import type { Settings } from "../../../../types/settings.js";
import { createLog } from "../../../logger/logger.js";

export let serverSettings: Settings[] = [];
const dbUrl = String(process.env.DATABASE_URL).replace("lst_db", "lst");
export const getSettings = async () => {
	const settingsType = process.env.LST_USE_GO;
	createLog(
		"info",
		"lst",
		"server",
		`Settings are being grabbed from the app now`,
	);
	const client = new Client({
		connectionString: dbUrl,
	});

	//if (settingsType !== "true") {
	try {
		//serverSettings = (await db.select().from(settings)) as any;

		await client.connect();

		if (serverSettings.length === 0) {
			try {
				const s = await client.query("SELECT * FROM settings");

				serverSettings = s.rows;
			} catch (e) {
				createLog(
					"error",
					"lst",
					"server",
					`There was an error getting the settings: ${JSON.stringify(e)}`,
				);
			}

			// const { data, error } = (await tryCatch(
			// 	axios.get(
			// 		`http://localhost:${process.env.VITE_SERVER_PORT}/lst/api/system/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;
		} else {
			return serverSettings;
		}
	} catch (error) {
		console.log(error);
		createLog(
			"error",
			"lst",
			"server",
			`There was an error getting the settings: ${JSON.stringify(error)}`,
		);
		//throw new Error("There was an error getting the settings");
	} finally {
		// ✅ Ensure the connection is always closed
		await client
			.end()
			.catch((e) =>
				createLog("error", "lst", "server", `Error closing DB client: ${e}`),
			);
	}
	//}

	//console.log(serverSettings);
	return serverSettings;
};
