import { db } from "../../../../database/dbclient.js";
import { users } from "../../../../database/schema/users.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { createLog } from "../../logger/logger.js";
import { setSysAdmin } from "../controllers/userRoles/setSysAdmin.js";
import { createPassword } from "./createPassword.js";

export const massAccountCreation = async () => {
    /**
     * This will create a new account for all users before if they are already in there it will update just there password.
     *
     */

    const user: any = [
        // {
        //     username: "landa002",
        //     email: "Oscar.Landa@alpla.com",
        //     password: "Frostlike-Petri5-Ungreased!",
        // },
    ];

    for (let i = 0; i < user.length; i++) {
        const updatedUser = {
            username: user[i].username,
            email: user[i].email,
            password: await createPassword(user[i].password),
        };
        const { data, error } = await tryCatch(
            db
                .insert(users)
                .values(updatedUser)
                .onConflictDoUpdate({
                    target: users.username,
                    set: {
                        password: updatedUser.password,
                        email: updatedUser.email,
                    },
                })
                .returning({
                    user_id: users.user_id,
                    username: users.username,
                })
        );

        await setSysAdmin(data, "systemAdmin");

        if (error) {
            createLog(
                "error",
                "lst",
                "auth",
                `There was an error creating ${user[i].username}`
            );
        }
    }
};
