import dsql from "@moduletrace/datasquirel";

type MysqlUser = {
    User: string;
    Host: string;
};

export default async function initSQLHandleRootUsers() {
    if (process.env.NEXT_PUBLIC_DSQL_LOCAL) {
        console.log("Production Environment. Root user setup not required");
        return;
    }

    const mainRootUser = await dsql.utils.connDbHandler<MysqlUser[]>(
        global.INIT_SQL_ROOT_DB_CONN,
        `SELECT user,host FROM mysql.user WHERE user='root' AND host=?`,
        [process.env.DSQL_DB_TARGET_IP_ADDRESS]
    );

    if (!mainRootUser?.[0]?.User) {
        console.log(`Main Root User Does not Exit.`);

        const createMainRootUser = await dsql.utils.connDbHandler<any[]>(
            global.INIT_SQL_ROOT_DB_CONN,
            [
                {
                    query: `CREATE USER IF NOT EXISTS \
                            'root'@'${process.env.DSQL_DB_TARGET_IP_ADDRESS}' \
                            IDENTIFIED BY '${process.env.DSQL_DB_PASSWORD}'`,
                },
                {
                    query: `GRANT ALL PRIVILEGES ON *.* TO 'root'@'${process.env.DSQL_DB_TARGET_IP_ADDRESS}' \
                            WITH GRANT OPTION`,
                },
                {
                    query: `FLUSH PRIVILEGES`,
                },
            ]
        );

        console.log("createMainRootUser", createMainRootUser);

        const checkRootUser = await dsql.utils.connDbHandler<MysqlUser[]>(
            global.INIT_SQL_ROOT_DB_CONN,
            `SELECT user,host FROM mysql.user WHERE user='root' AND host='${process.env.DSQL_DB_TARGET_IP_ADDRESS}'`
        );

        if (checkRootUser?.[0]?.User) {
            const dropWildcardRootUser = await dsql.utils.connDbHandler<
                MysqlUser[]
            >(global.INIT_SQL_ROOT_DB_CONN, "drop user 'root'@'%'");

            console.log("dropWildcardRootUser", dropWildcardRootUser);
        }
    } else {
        console.log("Root User Exists");
    }
}
