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";

/**
 * # Create database from Schema Function
 */
async function resetSQLCredentialsPasswords() {
    const users = (await dbHandler({
        query: `SELECT * FROM users`,
    })) as any[];

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

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

        if (!user) continue;

        const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";

        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(
                `SET PASSWORD FOR '${username}'@'${defaultMariadbUserHost}' = PASSWORD('${password}')`
            );

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

            console.log(
                `User ${user.id}: ${user.first_name} ${user.last_name} Password Updated successfully added.`
            );
        } catch (error: any) {
            console.log(
                `Error Updating User ${user.id} Password =>`,
                error.message
            );
        }
    }

    process.exit();
}

resetSQLCredentialsPasswords();
