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

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

/**
 * # Full Access Db Handler
 */
export default async function fullAccessDbHandler({
    queryString,
    tableSchema,
    queryValuesArray,
    forceLocal,
}: Param) {
    /**
     * Declare variables
     *
     * @description Declare "results" variable
     */
    let results;

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

    /**
     * Fetch from db
     *
     * @description Fetch data from db if no cache
     */
    try {
        results = await connDbHandler(DB_CONN, queryString, queryValuesArray);

        ////////////////////////////////////////
    } catch (error: any) {
        ////////////////////////////////////////

        serverError({
            component: "fullAccessDbHandler",
            message: error.message,
        });

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

    /**
     * Return results
     *
     * @description Return results add to cache if "req" param is passed
     */
    if (results && tableSchema) {
        const unparsedResults = results;
        const parsedResults = await parseDbResults({
            unparsedResults: unparsedResults,
            tableSchema: tableSchema,
        });
        return parsedResults;
    } else if (results) {
        return results;
    } else {
        return null;
    }
}
