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

export interface Comment {
    text: string,
    user: number
}
export interface Ticket {
    name: string;
    id: number;
    description: string;
    status: string;
    creation_date: string;
    comments: Comment[]
}
const router = Router();

router.get("/similarTickets/:search", async (req, res) => {
    const query = await connection.query("SELECT * FROM tickets;")
    const search = req.params.search.toLowerCase();

    const allTickets = (query[0] as Ticket[]).filter(z => {
        if(z.name.toLowerCase().includes(search) || 
           search.includes(z.name.toLowerCase()) || 
           z.description.toLowerCase().includes(search) || 
           search.includes(z.description.toLowerCase())
        ) {
            return true;
        } else {
            return false;
        }
    })
    res.json(allTickets.map(z => {
        return {
            ...z,
            comments: JSON.parse(z.comments as unknown as string)
        }
    }))
})

router.get("/all", async (req, res) => {
    const query = await connection.query("SELECT * FROM tickets;")
    res.json((query[0] as Ticket[]).map(z => {
        return {
            ...z,
            comments: JSON.parse(z.comments as unknown as string)
        }
    }))
})

router.get("/get/:id", async (req, res) => {
    const query = await connection.query("SELECT * FROM tickets WHERE id = ?;", [req.params.id])
    res.json((query[0] as Ticket[]).map(z => {
        return {
            ...z,
            comments: JSON.parse(z.comments as unknown as string)
        }
    }))
})

router.get("/yourTickets", forceAuthorization, async (req: RequestWithUser, res) => {
    const query = await connection.query("SELECT * FROM tickets WHERE created_by = ?;", [req.user?.id])
    res.json((query[0] as Ticket[]).map(z => {
        return {
            ...z,
            comments: JSON.parse(z.comments as unknown as string)
        }
    }))
})
export default  router;