import { eq } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { users } from "../../../../../database/schema/users.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import type { User } from "../../../../types/users.js";
import { createPassword } from "../../utils/createPassword.js";
import { createLog } from "../../../logger/logger.js";
import { sendEmail } from "../../../notifications/controller/sendMail.js";
import { settings } from "../../../../../database/schema/settings.js";
import { getSettings } from "../../../server/controller/settings/getSettings.js";

export const updateUserADM = async (userData: User) => {
    /**
     * The user model will need to be passed over so we can update per the request on the user.
     * password, username, email.
     */

    createLog(
        "info",
        "apiAuthedRoute",
        "auth",
        `${userData.user_id} is being updated.`
    );
    // get the orignal user info
    const { data: user, error: userError } = await tryCatch(
        db.select().from(users).where(eq(users.user_id, userData.user_id!))
    );

    if (userError) {
        return {
            success: false,
            message: "There was an error getting the user",
            userError,
        };
    }
    if (user?.length === 0) {
        return {
            success: false,
            message:
                "The user you are looking for has either been deleted or dose not exist.",
        };
    }

    //const { data: s, error: se } = await tryCatch(db.select().from(settings));
    const { data: s, error: se } = await tryCatch(getSettings());
    if (se) {
        return {
            success: false,
            message: `There was an error getting setting data to post to the server.`,
            data: se,
        };
    }

    const set: any = s;
    const server = set.filter((n: any) => n.name === "server");
    const port = set.filter((n: any) => n.name === "serverPort");

    const upd_user = user as User;
    const password: string = userData.password
        ? await createPassword(userData.password!)
        : upd_user.password!;
    const data = {
        username: userData.username ? userData.username : upd_user?.username,
        password: password,
        email: userData.email ? userData.email : upd_user.email,
        role: userData.role ? userData.role : upd_user.role,
    };

    // term ? ilike(posts.title, term) : undefined
    const { data: updData, error: updError } = await tryCatch(
        db.update(users).set(data).where(eq(users.user_id, userData.user_id!))
    );

    if (updError) {
        return {
            success: false,
            message: "There was an error getting the user",
            updError,
        };
    }

    if (userData?.password!.length > 0) {
        // send this user an email so they have the randomized password.
        await sendEmail({
            email: user[0]?.email,
            subject: "LST - Password reset.",
            template: "passwordReset",
            context: {
                password: userData.password!,
                username: user[0].username!,
                server: server[0].value,
                port: port[0].value,
            },
        });
    }

    return {
        success: true,
        message: `${userData.username} has been updated.`,
        updData,
    };
};
