require("dotenv").config({ path: "./../.env" });
import mysql from "serverless-mysql";
import grabDSQLConnection from "../utils/grab-dsql-connection";

/**
 * # Main DB Handler Function
 * @async
 *
 * @param {object} params
 * @param {string} params.query
 * @param {string[] | object} [params.values]
 * @param {string} [params.database]
 *
 * @returns {Promise<object|null>}
 */
(async () => {
    const CONNECTION = grabDSQLConnection();

    try {
        const result = await CONNECTION.query(
            "SELECT user,host,ssl_type FROM mysql.user"
        );
        const parsedResults = JSON.parse(JSON.stringify(result));

        for (let i = 0; i < parsedResults.length; i++) {
            const user = parsedResults[i];

            if (
                user.User !== process.env.DSQL_DB_READ_ONLY_USERNAME ||
                user.User !== process.env.DSQL_DB_FULL_ACCESS_USERNAME ||
                !user.User?.match(/dsql_user_.*/i)
            ) {
                continue;
            }

            const { User, Host, ssl_type } = user;

            if (ssl_type === "ANY") {
                continue;
            }

            const addUserSSL = await CONNECTION.query(
                `ALTER USER '${User}'@'${Host}'`
            );

            console.log(`addUserSSL => ${User}@${Host}`, addUserSSL);
        }
    } catch (error: any) {
        console.log("Connection query ERROR =>", error.message);
    } finally {
        CONNECTION.end();
        process.exit();
    }
})();
