const {Application} = require("../core/server");
const Joi = require("joi");
const { PostDataProcess } = require("../core/postdata");
const User = require("../database/user");
const { MiddlewareAuth } = require("./auth");
const express = require("express");
const { countCatalogs, getCatalogs, createCatalog, updateCatalog, deleteCatalogs } = require("../database/catalog");


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

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

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

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

    try{
        await updateCatalog(
            request.body.id,
            request.session.user_id,
            request.body.name,
            request.body.score,
            request.body.description
        );
        return response.status(200).json({
            status: "success"
        });
    }catch(err){
        console.log(err)
        return response.status(500).json({
            status: "fail"
        });
    }
}


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

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

    try{
        await createCatalog(
            request.session.user_id,
            request.body.name,
            request.body.score,
            request.body.description
        );
        return response.status(200).json({
            status: "success"
        });
    }catch(err){
        console.log(err)
        return response.status(500).json({
            status: "fail"
        });
    }
}

function catalogStoreValidation(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')),
        score: Joi.number().min(1).allow('', null).error(new Error('Soyadı formatı hatalı')),
        description: Joi.string().allow('', null)
    });
    const {error} = schema.validate(body);
    return error;
}

Application.post("/catalogs/destroy", MiddlewareAuth, express.urlencoded({extended: true}), CatalogDestroy);
/**
 * @param {import("express").Request} request
 * @param {import("express").Response} response
 */
async function CatalogDestroy(request, response)
{
    try{
        await deleteCatalogs(
            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"
        });
    }
}