const crypto = require("node:crypto");
const DB = require("./connection");


exports.createUser = createUser;
exports.hasUser = hasUser;
exports.getUser = getUser;
exports.checkUser = checkUser;

async function createUser(
    name,
    surname,
    email,
    password
)
{
    const [id] = await DB.table("users")
        .insert({
            name,
            surname,
            email,
            password: sha256(password)
        })
        .returning("id");
    return id;
}
async function hasUser(email)
{
    let data = await DB.table("users")
        .select("id")
        .where("email",email)
        .whereNull("deleted_at")
        .first();
    return data != null;
}
async function checkUser(email,password)
{
    password = sha256(password);
    let data = await DB.table("users")
        .select("id")
        .where("email",email)
        .where("password",password)
        .whereNull("deleted_at")
        .first();
    return data;
}
async function getUser(id)
{
    return await DB.table("users")
        .where("id",id)
        .whereNull("deleted_at")
        .first();
}

function sha256(key)
{
    return crypto.createHash("sha256").update(key).digest("hex");
}
/*
        table.string('name').notNullable();
        table.string('surname').notNullable();
        table.string('email').unique().index();
        table.string('password',255).notNullable();
        table.dateTime("created_at").defaultTo(knex.fn.now());;
        table.dateTime("update_at").defaultTo(knex.fn.now());;
        table.dateTime("deleted_at");
*/