import parseDbResults from "./parseDbResults";
import serverError from "./serverError";
import grabDSQLConnection from "../../utils/grab-dsql-connection";
import connDbHandler from "../../utils/db/conn-db-handler";

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

/**
 * # DB handler for specific database
 */
export default async function varDatabaseDbHandler({
    queryString,
    queryValuesArray,
    database,
    tableSchema,
    debug,
}: Param): Promise<any> {
    let CONNECTION = grabDSQLConnection({ fa: true });
    if (global.DSQL_USE_LOCAL) CONNECTION = grabDSQLConnection({ local: true });
    if (database?.match(/^datasquirel$/)) CONNECTION = grabDSQLConnection();

    if (debug) {
        console.log(`varDatabaseDbHandler:query:`, queryString);
        console.log(`varDatabaseDbHandler:values:`, queryValuesArray);
        console.log(`varDatabaseDbHandler:CONNECTION:`, CONNECTION.getConfig());
    }

    let results = await connDbHandler(
        CONNECTION,
        queryString,
        queryValuesArray
    );

    if (debug) {
        console.log(`varDatabaseDbHandler:results:`, results);
    }

    if (results && tableSchema) {
        try {
            const unparsedResults = results;
            const parsedResults = await parseDbResults({
                unparsedResults: unparsedResults,
                tableSchema: tableSchema,
            });
            return parsedResults;
        } catch (error: any) {
            console.log(
                "\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>",
                database,
                error
            );
            serverError({
                component: "varDatabaseDbHandler/lines-52-53",
                message: error.message,
            });
            return null;
        }
    } else if (results) {
        return results;
    } else {
        return null;
    }
}
