import { json, Router } from "express";
import { forceAuthorization, type RequestWithUser } from "./authentication";
import { connection } from "..";
import type { Comment, Ticket } from "./ticket_lists";

const router = Router();

router.post("/edit", forceAuthorization, json(), async (req: RequestWithUser, res) => {
    const body = req.body;
    if(!body.id) { res.status(400).json({
        error: "No ID found."
    }); return }
    if(typeof body.id != "number") { res.status(400).json({
        error: "ID is not a number."
    }); return }

    if(!req.user?.admin) {
        res.status(400).json({
            error: "You are not a administrator."
        }); 
        return;
    }
    const elements = [
        ["name", body.name],
        ["description", body.description],
        ["status", body.status]
    ]

    let update = "UPDATE `tickets` SET ";
    const updateArray = [];
    const order = [];

    for(const element of elements) {
        if(element[1]) {
            updateArray.push(`\`${element[0]}\` = ?`)
            order.push(element[1])
        }
    }
    
    update += updateArray.join(", ") + " WHERE `tickets`.`id` = ?;"

    order.push(body.id);

    await connection.query(update, order);

    res.status(201).end();
})

router.post("/addComment", forceAuthorization, json(), async (req: RequestWithUser, res) => {
    const body = req.body;
    if(!body.id) { res.status(400).json({
        error: "No ticket ID found."
    }); return }
    if(!body.text) { res.status(400).json({
        error: "No comment text found."
    }); return }

    const ticketQuery = await connection.query("SELECT * FROM tickets WHERE id = ?;", [body.id]);
    const ticketResult = ticketQuery[0] as Ticket[]
    if(ticketResult.length == 0) {
        res.status(400).json({
            error: "Ticket does not exist."
        })
        return;
    }
    
    const ticket = ticketResult[0];
    const comments = JSON.parse(ticket.comments as unknown as string);

    comments.push({
        text: body.text,
        user: req.user?.id
    })

    ticket.comments = JSON.stringify(comments) as unknown as Comment[];

    await connection.query("UPDATE `tickets` SET `comments` = ? WHERE `tickets`.`id` = ?", [
        ticket.comments,
        ticket.id
    ])
    res.status(201).end();
});

export default  router;