import {genSalt, hash, compare} from "bcrypt";
import { DB } from "sqlite";

interface User{
    name: string;
    salted_password: string;
    salt: string;
}

export async function createUser(name: string, password: string){
    const salt = await genSalt(10);
    const salted_password = await hash(password, salt);
    const user: User = {
        name: name,
        salted_password: salted_password,
        salt: salt
    }
    return user;
}

export async function verifyUser(user: User, password: string){
    return await compare(password, user.salted_password);
}

export async function getAllUsers(db :DB): Promise<User[]>{
    const users = await db.query<[string, string, string]>
        ("SELECT name, salted_password, salt FROM users");
    return users.map(([name, salted_password, salt])=>({
        name,
        salted_password,
        salt,
    }));
}

export async function getUser(db: DB, name: string): Promise<User | undefined>{
    const users = await db.query<[string, string, string]>
        ("SELECT name, salted_password, salt FROM users WHERE name = ?", [name]);
    if (users === undefined || users.length === 0){
        return undefined;
    }
    const user = users[0];
    return {
        name: user[0],
        salted_password: user[1],
        salt: user[2],
    }
}

export async function addUser(db: DB, user: User){
    await db.query("INSERT INTO users (name, salted_password, salt) VALUES (?, ?, ?)", 
        [user.name, user.salted_password, user.salt]);
}

export async function updateUser(db: DB, user: User){
    await db.query("UPDATE users SET salted_password = ?, salt = ? WHERE name = ?", 
        [user.salted_password, user.salt, user.name]);
}

export async function deleteUser(db: DB, name: string){
    await db.query("DELETE FROM users WHERE name = ?", [name]);
}

export async function createSchema(db: DB){
    await db.query("CREATE TABLE IF NOT EXISTS users (name TEXT PRIMARY KEY, salted_password TEXT, salt TEXT)");
}