import execute from "../../docker/setup/(utils)/execute";
import mysql, { ServerlessMysql } from "serverless-mysql";
import initSQLHandleRootUsers from "./(functions)/handle-root-user";
import initSQLCheckEnvVariables from "./(functions)/check-env-variables";
import initSQLCreateDatabases from "./(functions)/create-databases";
import initSQLCheckDsqlUsers from "./(functions)/check-dsql-users";

console.log(`Initializing Database ...`);
console.log(`DB HOST =>  ${process.env.DSQL_DB_HOST}`);

/**
 * # Declare Global Variables
 */
declare global {
    var INIT_SQL_ROOT_DB_CONN: ServerlessMysql;
    var INIT_SQL_MAIN_DB_CONN: ServerlessMysql;
}

/**
 * # Ping Database Function
 */
function pingDb() {
    return execute(
        `mysqladmin ping -h"${process.env.DSQL_DB_HOST}" -u"root" -p"${process.env.DSQL_MARIADB_ROOT_PASSWORD}" --silent`
    );
}

/**
 * # Check MariaDB Availability
 */
let tries = 0;

while (true) {
    if (tries > 10) {
        process.exit(2);
    }

    const checkDb = pingDb();

    if (checkDb?.match(/alive/)) break;

    tries++;

    await Bun.sleep(2000);
}

console.log("MariaDB is ready!");

/**
 * # Check Environment Variables
 */
await initSQLCheckEnvVariables();

/**
 * # Handle Root Users
 */
global.INIT_SQL_ROOT_DB_CONN = mysql({
    config: {
        host: process.env.DSQL_DB_HOST,
        user: "root",
        password: process.env.DSQL_MARIADB_ROOT_PASSWORD,
        charset: "utf8mb4",
    },
});

await initSQLHandleRootUsers();

/**
 * # Handle Operations with New Root User
 */
global.INIT_SQL_MAIN_DB_CONN = mysql({
    config: {
        host: process.env.DSQL_DB_HOST,
        user: "root",
        password: process.env.DSQL_DB_PASSWORD,
        charset: "utf8mb4",
    },
});

await initSQLCreateDatabases();
await initSQLCheckDsqlUsers();

/**
 * # All Done. Exit With Success.
 */
process.exit(0);