import fs from "fs";
import path from "path";
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 (error: any) {
        if (process.env.FIRST_RUN) {
            return null;
        }

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

        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;
    } finally {
        await CONNECTION?.end();
    }

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