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

const router = Router()

router.post("/create", forceAuthorization, json(), async (req: RequestWithUser, res) => {
    const body = req.body;
    if(!body.name) { res.status(400).json({
        error: "No ticket name."
    }); return }
    if(typeof body.name != "string") { res.status(400).json({
        error: "Ticket name is not a string."
    }); return }

    if(!body.description) { res.status(400).json({
        error: "No description set."
    }); return }
    if(typeof body.description != "string") { res.status(400).json({
        error: "Description is not a string."
    }); return }
    
    await connection.query("INSERT INTO `tickets` (`id`, `name`, `description`, `status`, `creation_date`, `comments`, `created_by`) VALUES (NULL, ?, ?, ?, ?, '[]', ?);", [body.name, body.description, "Submitted", new Date().toISOString().replace("T", " ").replace("Z", ""), req.user?.id])
    res.status(201).end();
})

export default  router;