import { returnFunc } from "../utils/return.js";
import { connected, pool } from "./prodSqlConnect.js";
import { validateEnv } from "../utils/envValidator.js";

const env = validateEnv(process.env);
/**
 * 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 async function prodQuery(queryToRun: string, name: string) {
    if (!connected) {
        return returnFunc({
            success: false,
            module: "prodSql",
            subModule: "query",
            level: "error",
            message: `The sql ${env.PROD_PLANT_TOKEN} is not connected`,
            notify: false,
            data: [],
        });
    }
    const query = queryToRun.replaceAll("test1", env.PROD_PLANT_TOKEN);
    try {
        const result = await pool.request().query(query);
        return {
            success: true,
            message: `Query results for: ${name}`,
            data: result.recordset,
        };
    } catch (error: any) {
        console.log(error);
        if (error.code === "ETIMEOUT") {
            return returnFunc({
                success: false,
                module: "prodSql",
                subModule: "query",
                level: "error",
                message: `${name} did not run due to a timeout.`,
                notify: false,
                data: [error],
            });
        }

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