import fs from "fs";
import serverError from "./serverError";

/**
 * # Main DB Handler Function
 */
export default async function dbHandler(...args: any[]) {
    process.env.NODE_ENV?.match(/dev/) &&
        fs.appendFileSync(
            "./.tmp/sqlQuery.sql",
            args[0] + "\n" + Date() + "\n\n\n",
            "utf8"
        );

    let results;

    /**
     * Fetch from db
     *
     * @description Fetch data from db if no cache
     */
    try {
        const connection = global.DSQL_DB_CONN;

        results = await new Promise((resolve, reject) => {
            connection.query(
                ...args,
                (error: any, result: any, fields: any) => {
                    if (error) {
                        resolve({ error: error.message });
                    } else {
                        resolve(result);
                    }
                }
            );
        });

        await connection.end();
    } catch (error: any) {
        fs.appendFileSync(
            "./.tmp/dbErrorLogs.txt",
            JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n",
            "utf8"
        );

        results = null;

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

    /**
     * Return results
     *
     * @description Return results add to cache if "req" param is passed
     */
    if (results) {
        return JSON.parse(JSON.stringify(results));
    } else {
        return null;
    }
}