import { eq } from "drizzle-orm";
import { db } from "../../../../database/dbclient.js";
import { users } from "../../../../database/schema/users.js";
import { createPassword } from "../utils/createPassword.js";
import { setSysAdmin } from "./userRoles/setSysAdmin.js";
import { createLog } from "../../logger/logger.js";

export const registerUser = async (
    username: string,
    password: string,
    email: string
) => {
    const usercount = await db.select().from(users);

    // make sure the user dose not already exist in the system
    const userCheck = await db
        .select()
        .from(users)
        .where(eq(users.username, username));

    if (userCheck.length === 1) {
        return {
            success: false,
            message: `${username} already exists please login or reset password, if you feel this is an error please contact your admin.`,
        };
    }

    // make sure we only send over a username that is all lowercase
    username = username.toLowerCase();

    // get the good kinda password
    password = await createPassword(password);

    try {
        const user = await db
            .insert(users)
            .values({ username, email, password })
            .returning({ user: users.username, email: users.email });

        if (usercount.length === 0) {
            createLog(
                "info",
                "auth",
                "auth",
                `${username} is the first user and will be set to system admin.`
            );
            const updateUser = await db
                .select()
                .from(users)
                .where(eq(users.username, username));
            setSysAdmin(updateUser, "systemAdmin");
        }

        return { success: true, message: "User Registered", user };
    } catch (error) {
        createLog("error", "auth", "auth", `${error}`);
        return {
            success: false,
            message: `${username} already exists please login or reset password, if you feel this is an error please contact your admin.`,
        };
    }
};
