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

const blacklistedTokens = new Set();

function blacklistToken(token: string) {
    blacklistedTokens.add(token);
    setTimeout(() => blacklistedTokens.delete(token), 3600 * 1000); // Remove after 1 hour
}

function isTokenBlacklisted(token: string) {
    return blacklistedTokens.has(token);
}

export const updateProfile = async (user: any, data: any, token: string) => {
    if (isTokenBlacklisted(token)) {
        createLog("warn", user.username, "auth", `${user.username} is trying to use a black listed token`);
        throw Error("This token was already used");
    }

    //re salt and encrypt the password
    try {
        const saltPass = await createPassword(data.password);
        // update the password
        const profileUpdate = await db
        .update(users)
        .set({password: saltPass, upd_user: user.username, upd_date: sql`NOW()`})
        .where(eq(users.user_id, user.user_id));

        blacklistToken(token);
    } catch (error) {
        createLog(
            "error",
            user.username,
            "auth",
            `Error: ${JSON.stringify(error)}, "There was an error updating the users profile"`
        );
    }
};
