const express = require('express');
const { getConnection, getUsers, getUserByUsername, getUserLastMessages, getMentions, deleteUser, deleteUserMessages, deleteUserMentions } = require('../libs/mysql');
const { checkAuth } = require("../libs/middlewares")

const router = express.Router();

router.get('/', async (req, res) => {
    const connection = await getConnection();
    const users = await getUsers(connection);
    connection.end();
    res.send(users);
});

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);
});

router.use("/:username/delete", checkAuth);
router.post('/:username/delete', async (req, res) => {
    const username = req.params.username;
    const user = req.user;

    const connection = await getConnection();

    const userToDelete = await getUserByUsername(connection, username);

    if (!userToDelete[0]) {
        connection.end();
        return res.status(400).send({ error: 'No user found' });
    }

    if (user.admin !== 1) {
        connection.end();
        return res.status(401).send({ error: 'Unauthorized' });
    }

    await deleteUserMentions(connection, userToDelete[0].id);
    await deleteUserMessages(connection, userToDelete[0].id);
    await deleteUser(connection, userToDelete[0].id);

    connection.end();

    req.sockets.emit({
        type: 'delete_user',
        user_id: userToDelete[0].id,
    });

    res.send({ message: 'User deleted' });
});

module.exports = router;