import { returnFunc } from "../utils/returnHelper.utils.js";
import { connected, pool2 } from "./gpSqlConnection.controller.js";

interface SqlError extends Error {
	code?: string;
	originalError?: {
		info?: { message?: string };
	};
}

/**
 * Run a prod query
 * just pass over the query as a string and the name of the query.
 * Query should be like below.
 *  * select * from AlplaPROD_test1.dbo.table
 * You must use test1 always as it will be changed via query
 */
export const gpQuery = async (queryToRun: string, name: string) => {
	if (!connected) {
		return returnFunc({
			success: false,
			level: "error",
			module: "system",
			subModule: "gpSql",
			message: `${process.env.PROD_PLANT_TOKEN} is offline or attempting to reconnect`,
			data: [],
			notify: false,
		});
	}

	//change to the correct server
	const query = queryToRun.replaceAll(
		"test1",
		`${process.env.PROD_PLANT_TOKEN}`,
	);

	try {
		const result = await pool2.request().query(query);
		return {
			success: true,
			message: `Query results for: ${name}`,
			data: result.recordset ?? [],
		};
	} catch (error: unknown) {
		const err = error as SqlError;
		if (err.code === "ETIMEOUT") {
			return returnFunc({
				success: false,
				module: "system",
				subModule: "gpSql",
				level: "error",
				message: `${name} did not run due to a timeout.`,
				notify: false,
				data: [],
			});
		}

		if (err.code === "EREQUEST") {
			return returnFunc({
				success: false,
				module: "system",
				subModule: "gpSql",
				level: "error",
				message: `${name} encountered an error ${err.originalError?.info?.message || "undefined error"}`,
				data: [],
			});
		}

		return returnFunc({
			success: false,
			module: "system",
			subModule: "gpSql",
			level: "error",
			message: `${name} encountered an unknown error.`,
			data: [],
		});
	}
};
