import fs from "fs";
import path from "path";

import mysql from "serverless-mysql";
import grabDbSSL from "../../utils/backend/grabDbSSL";
import grabDSQLConnection from "../../utils/grab-dsql-connection";

type Param = {
    query: string;
    values?: string[] | object;
};

/**
 * # Main DB Handler Function
 * @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
 */
export default async function dbHandler({
    query,
    values,
}: Param): Promise<any[] | object | null> {
    const CONNECTION = grabDSQLConnection();

    let results;

    try {
        if (query && values) {
            results = await CONNECTION.query(query, values);
        } else {
            results = await CONNECTION.query(query);
        }
    } catch (/** @type {any} */ error: any) {
        if (process.env.FIRST_RUN) {
            return null;
        }

        console.log("ERROR in dbHandler =>", error.message);
        console.log(error);
        console.log(CONNECTION.config());

        fs.appendFileSync(
            path.resolve(__dirname, "../.tmp/dbErrorLogs.txt"),
            JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n",
            "utf8"
        );
        results = null;
    } finally {
        await CONNECTION?.end();
    }

    if (results) {
        return JSON.parse(JSON.stringify(results));
    } else {
        return null;
    }
}