const express = require('express');
const { getConnection, getUserByUsername, getUserLastMessages, getMentions } = require('../libs/mysql');

const router = express.Router();

router.get('/:username', async (req, res) => {
    const username = req.params.username;
    const connection = await getConnection();
    const user = await getUserByUsername(connection, username);
    connection.end();
    if (user[0]) {
        res.send({id: user[0].id, username: user[0].username, admin: user[0].admin});
    } else {
        res.send('No user found');
    }
});

router.get('/:username/lastmessages', async (req, res) => {
    const username = req.params.username;
    const connection = await getConnection();
    const messages = await getUserLastMessages(connection, username);

    for (const message of messages) {
        if (message.content.includes('@')) {
            const mentions = await getMentions(connection, message.id);
            message.mentions = mentions;
        } else {
            message.mentions = [];
        }
    }

    connection.end();
    res.send(messages);
});

module.exports = router;