import serverError from "./serverError";
import parseDbResults from "./parseDbResults";
import connDbHandler from "../../utils/db/conn-db-handler";

type Param = {
    queryString: string;
    queryValuesArray?: string[];
    tableSchema?: import("../../types").DSQL_TableSchemaType;
    forceLocal?: boolean;
};

/**
 * # Read Only Db Handler with Varaibles
 * @returns
 */
export default async function varReadOnlyDatabaseDbHandler({
    queryString,
    queryValuesArray,
    tableSchema,
    forceLocal,
}: Param) {
    let results;

    const DB_CONN = forceLocal
        ? global.DSQL_DB_CONN
        : global.DSQL_READ_ONLY_DB_CONN || global.DSQL_DB_CONN;

    try {
        results = await connDbHandler(DB_CONN, queryString, queryValuesArray);
    } catch (error: any) {
        serverError({
            component: "varReadOnlyDatabaseDbHandler",
            message: error.message,
            noMail: true,
        });

        return error.message;
    } finally {
        DB_CONN?.end();
    }

    if (results) {
        const unparsedResults = results;
        const parsedResults = await parseDbResults({
            unparsedResults: unparsedResults,
            tableSchema: tableSchema,
        });
        return parsedResults;
    } else {
        return null;
    }
}
