const {Application} = require("../core/server");
const Joi = require("joi");
const { PostDataProcess } = require("../core/postdata");
const User = require("../database/user");
const { MiddlewareAuth } = require("./auth");
const { createStudent, getStudents, countStudents, updateStudent, deleteStudent } = require("../database/student");
const express = require("express");


Application.get("/panel", MiddlewareAuth,PanelPage);
/**
 * @param {import("express").Request} request
 * @param {import("express").Response} response
 */
async function PanelPage(request, response)
{
    response.render("panel/panel");
}

Application.post("/user/profile", MiddlewareAuth,ApiUserProfile);
/**
 * @param {import("express").Request} request
 * @param {import("express").Response} response
 */
async function ApiUserProfile(request, response)
{
    let name = request.session.user.name;
    let surname = request.session.user.surname;
    
    response.json({
        status: "active",
        name,
        surname
    });
}


Application.get("/students", MiddlewareAuth,StudentsPage);
/**
 * @param {import("express").Request} request
 * @param {import("express").Response} response
 */
async function StudentsPage(request, response)
{
    response.render("panel/students");
}

Application.post("/students/store", MiddlewareAuth, PostDataProcess(), StudentStore);
/**
 * @param {import("express").Request} request
 * @param {import("express").Response} response
 */
async function StudentStore(request, response)
{
    const error = studentStoreValidation(request.body);

    if(error)
    {
        return response.status(400).json({
            status: "fail",
            message: error.message
        });
    }

    try{
        await createStudent(
            request.session.user_id,
            request.body.name,
            request.body.surname,
            request.body.studentno,
            request.body.email,
            request.body.gender,
            request.body.birthdate || null,
            request.body.description
        );
        return response.status(200).json({
            status: "success"
        });
    }catch(err){
        console.log(err)
        return response.status(500).json({
            status: "fail"
        });
    }
}

Application.post("/students/update", MiddlewareAuth, PostDataProcess(), StudentUpdate);
/**
 * @param {import("express").Request} request
 * @param {import("express").Response} response
 */
async function StudentUpdate(request, response)
{
    const error = studentStoreValidation(request.body);

    if(error)
    {
        return response.status(400).json({
            status: "fail",
            message: error.message
        });
    }

    try{
        await updateStudent(
            request.body.id,
            request.session.user_id,
            request.body.name,
            request.body.surname,
            request.body.studentno,
            request.body.email,
            request.body.gender,
            request.body.birthdate || null,
            request.body.description
        );
        return response.status(200).json({
            status: "success"
        });
    }catch(err){
        console.log(err)
        return response.status(500).json({
            status: "fail"
        });
    }
}
Application.post("/students/destroy", MiddlewareAuth, express.urlencoded({extended: true}), StudentDestroy);
/**
 * @param {import("express").Request} request
 * @param {import("express").Response} response
 */
async function StudentDestroy(request, response)
{
    try{
        await deleteStudent(
            request.session.user_id,
            request.body.id ?? -1
        );
        return response.status(200).json({
            status: "success"
        });
    }catch(err){
        console.log(err)
        return response.status(500).json({
            status: "fail"
        });
    }
}


Application.post("/students/list", MiddlewareAuth, express.urlencoded({extended: true}), StudentList);
/**
 * @param {import("express").Request} request
 * @param {import("express").Response} response
 */
async function StudentList(request, response)
{
    let start = request.body.start ?? 0;
    let length = request.body.length ?? 100;
    let term = request.body.search?.value ?? null;
    let count = await countStudents(request.session.user_id, term);
    let data = await getStudents(request.session.user_id,start,length, term);
    response.json({
        "draw": request.body.draw | 0,
        "recordsTotal": count,
        "recordsFiltered" : count,
        "data": data
    });
}


function studentStoreValidation(body)
{
    const schema = Joi.object({
        id: Joi.number().min(1),
        name: Joi.string().min(3).max(200).required().error(new Error('Adı en az 3 karakter ve zorunludur')),
        surname: Joi.string().max(200).allow('', null).error(new Error('Soyadı formatı hatalı')),
        studentno: Joi.string().max(200).allow('', null).error(new Error('Numara formatı hatalı')),
        email: Joi.string().email().max(200).allow('', null).error(new Error('E-posta adresi geçersiz')),
        birthdate: Joi.date().iso().allow('', null).error(new Error('Doğum tarihi geçersiz')),
        gender: Joi.string().valid('male', 'female', 'Belirtilmemiş').allow('', null).error(new Error('Cinsiyet seçimi hatalı')),
        description: Joi.string().allow('', null)
    });
    const {error} = schema.validate(body);
    return error;
}