require("dotenv").config({ path: "./../.env" });
import generator from "generate-password";
import noDatabaseDbHandler from "./utils/noDatabaseDbHandler";
import dbHandler from "./utils/dbHandler";
import encrypt from "../functions/dsql/encrypt";

/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */

/**
 * # Set SQL Credentials
 */
async function setSQLCredentials() {
    const users = (await dbHandler({
        query: `SELECT * FROM users`,
    })) as any[] | null;

    if (!users) {
        process.exit();
    }

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

        if (!user) continue;
        if (user.mariadb_user && user.mariadb_pass) {
            continue;
        }

        try {
            const username = `dsql_user_${user.id}`;
            const password = generator.generate({
                length: 16,
                numbers: true,
                symbols: true,
                uppercase: true,
                exclude: "*#.'`\"",
            });
            const encryptedPassword = encrypt({ data: password });

            await noDatabaseDbHandler(
                `CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}'`
            );

            await noDatabaseDbHandler(
                `GRANT ALL PRIVILEGES ON \`datasquirel\\_user\\_${user.id}\\_%\`.* TO '${username}'@'127.0.0.1'`
            );
            await noDatabaseDbHandler(`FLUSH PRIVILEGES`);

            const updateUser = await dbHandler({
                query: `UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1' mariadb_pass = ? WHERE id = ?`,
                values: [username, encryptedPassword, user.id],
            });

            console.log(
                `User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.`
            );
        } catch (error: any) {
            console.log(`Error in adding SQL user =>`, error.message);
        }
    }
}

setSQLCredentials();
