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


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

exports.createEvent = createEvent;
exports.countEvents = countEvents;
exports.getEvents = getEvents;
exports.deleteEvent = deleteEvent;
exports.getStudentScores = getStudentScores;



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 ?? ""}%`)
        .orderBy("created_at","desc")
        .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()
        });
}

async function createEvent(owner_id, studentid, catalogid)
{
    let student = await DB.table("students").where("owner_id",owner_id).where("id",studentid).whereNull("deleted_at").first();
    let catalog = await DB.table("events").where("owner_id",owner_id).where("id",catalogid).whereNull("deleted_at").first();

    if(student == null){
        throw "Öğrenci yok"
    }

    if(catalog == null){
        throw "Skor yok"
    }

    await DB.table("student_events").insert({
        owner_id: owner_id,
        student_id: student.id,
        event_id: catalog.id,
        score: catalog.score
    });
}

async function countEvents()
{
    return 0
}

async function getEvents(owner_id,start,length,searchTerm)
{
    return await DB
        .select([
            "student_events.id as id",
            "students.name as studentname",
            "students.surname as studentsurname",
            "student_events.score",
            "events.name as catalog",
            "student_events.created_at",
        ])
        .table("student_events")
        .innerJoin("students","students.id","=","student_id")
        .innerJoin("events","events.id","=","event_id")
        .where("student_events.owner_id",owner_id)
        .where(function(q){
            q.where("students.name","like",`%${searchTerm ?? ""}%`)
            q.orWhere("events.name","like",`%${searchTerm ?? ""}%`)
        })
        .orderBy("student_events.created_at","desc")
        .whereNull("student_events.deleted_at")
        .whereNull("students.deleted_at")
        .whereNull("events.deleted_at")
        .limit(length)
        .offset(start);
}

async function getStudentScores(owner_id, start, length, searchTerm)
{
    const students = await DB('students')
        .select([
            'id',
            'name',
            'surname',
            DB('student_events')
                .sum('score')
                .whereRaw('?? = ??', ['student_events.student_id', 'students.id'])
                .where('owner_id', owner_id)
                .whereNull('deleted_at')
                .as('total_score')
        ])
        .where("name","like",`%${searchTerm ?? ""}%`)
        .whereNull('deleted_at')
        .orderBy('total_score', 'desc')
        .limit(length)
        .offset(start);
    return students;
}

async function deleteEvent(owner_id, id)
{
    await DB.table("student_events")
        .where("owner_id",owner_id)
        .where("id",id)
        .update({
            deleted_at: DB.fn.now()
        });
}