import fs from "fs";
import serverError from "./serverError";
import grabDSQLConnection from "../../utils/grab-dsql-connection";
import path from "path";

/**
 * # 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"
        );

    const CONNECTION = grabDSQLConnection();

    let results;

    /**
     * Fetch from db
     *
     * @description Fetch data from db if no cache
     */
    try {
        results = await new Promise((resolve, reject) => {
            CONNECTION.query(
                ...args,
                (error: any, result: any, fields: any) => {
                    if (error) {
                        resolve({ error: error.message });
                    } else {
                        resolve(result);
                    }
                }
            );
        });
    } catch (error: any) {
        const tmpFolder = path.resolve(process.cwd(), "./.tmp");
        if (!fs.existsSync(tmpFolder))
            fs.mkdirSync(tmpFolder, { recursive: true });

        fs.appendFileSync(
            path.resolve(tmpFolder, "./dbErrorLogs.txt"),
            JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n",
            "utf8"
        );

        results = null;

        serverError({
            component: "dbHandler",
            message: error.message,
        });
    } finally {
        await CONNECTION?.end();
    }

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