import { pbkdf2Sync, randomBytes } from "crypto";

import { Db } from "mongodb";

import { IUser } from "../models/user";

export async function isAuthenticated(token: string, db: Db): Promise<boolean> {
    // See if we can find a session with that token
    const session = await db.collection("sessions").findOne({ token, });
    return session !== null;
}

export async function performLogin(username: string, password: string, db: Db): Promise<IUser> {
    const user = await db.collection("users").findOne({
        username,
    });

    // Hash the password
    const hash = pbkdf2Sync(password, user.salt, 50000, 512, "sha512").toString("hex");
    if (hash === user.hash) {
        // Create a session
        const sessionToken = randomBytes(20).toString("hex");

        // Store the token
        await db.collection("sessions").insertOne({
            username: user.username,
            token: sessionToken,
        });

        // Return the user, but remove all undeeded data
        let copy = Object.assign({}, user, {
            sessionToken,
        });
        delete copy._id;
        delete copy.hash;
        delete copy.salt;
        delete copy.lastReview;
        delete copy.lastLevel;
        delete copy.vocabMetadata;


        return copy;
    } else {
        // It does not matter what we throw
        throw new Error("LOL");
    }
};
