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


exports.createStudent = createStudent;
exports.getStudents = getStudents;
exports.countStudents = countStudents;
exports.updateStudent = updateStudent;
exports.deleteStudent = deleteStudent;


async function createStudent(
    owner_id,
    name,
    surname,
    studentno,
    email,
    gender,
    birthdate,
    description
)
{
    const [id] = await DB.table("students")
        .insert({
            owner_id,
            name,
            surname,
            studentno,
            email,
            gender,
            birthdate,
            description
        })
        .returning("id");
    return id;
}
async function updateStudent(
    id,
    owner_id,
    name,
    surname,
    studentno,
    email,
    gender,
    birthdate,
    description
)
{
    await DB.table("students")
        .where("id",id)
        .where("owner_id", owner_id)
        .update({
            name,
            surname,
            studentno,
            email,
            gender,
            birthdate,
            description
        });
}




async function getStudents(
    owner_id,
    offset,
    limit,
    searchTerm
)
{
    return await DB.table("students")
        .where("owner_id",owner_id)
        .whereNull("deleted_at")
        .where("name","like",`%${searchTerm ?? ""}%`)
        .limit(limit)
        .offset(offset);
}
async function countStudents(owner_id, searchTerm)
{
    return (
        await DB.table("students")
        .where("owner_id",owner_id)
        .whereNull("deleted_at")
        .where("name","like",`%${searchTerm ?? ""}%`)
        .count("id as total")
        .first()
    ).total;
}
async function deleteStudent(owner_id, id)
{
    await DB.table("students")
        .where("owner_id",owner_id)
        .where("id",id)
        .update({
            deleted_at: DB.fn.now()
        });
}