require("dotenv").config({ path: "./../.env" });
import serverError from "../functions/backend/serverError";
import noDatabaseDbHandler from "./utils/noDatabaseDbHandler";

/**
 * # Create Database From Schema
 */
async function grantFullPrivileges({ userId }: { userId: string | null }) {
    /**
     * Grab Schema
     *
     * @description Grab Schema
     */
    try {
        const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";

        const allDatabases = await noDatabaseDbHandler(`SHOW DATABASES`);

        const datasquirelUserDatabases = allDatabases.filter(
            (/** @type {any} */ database: any) =>
                database.Database.match(/datasquirel_user_/)
        );

        for (let i = 0; i < datasquirelUserDatabases.length; i++) {
            const datasquirelUserDatabase = datasquirelUserDatabases[i];
            const { Database } = datasquirelUserDatabase;

            const grantDbPriviledges = await noDatabaseDbHandler(
                `GRANT ALL PRIVILEGES ON ${Database}.* TO '${process.env.DSQL_DB_FULL_ACCESS_USERNAME}'@'%' WITH GRANT OPTION`
            );

            const grantRead = await noDatabaseDbHandler(
                `GRANT SELECT ON ${Database}.* TO '${process.env.DSQL_DB_READ_ONLY_USERNAME}'@'%'`
            );
        }

        const flushPriviledged = await noDatabaseDbHandler(`FLUSH PRIVILEGES`);
    } catch (/** @type {any} */ error: any) {
        serverError({
            component: "shell/grantDbPriviledges/main-catch-error",
            message: error.message,
            user: { id: userId },
        });
    }

    process.exit();
}

const userArg = process.argv[process.argv.indexOf("--user")];
const externalUser = process.argv[process.argv.indexOf("--user") + 1];

grantFullPrivileges({ userId: userArg ? externalUser : null });
