const express = require('express');
const { WebhookClient, EmbedBuilder } = require('discord.js');
const { getUsername } = require('../functions/utils.js');
const { Users } = require('../functions/models.js');

const router = express.Router();
const webhookClient = new WebhookClient({ url: process.env.MINECRAFT_WEBHOOK_URL });

router.post('/player', async (req, res) => {
  const { content, uuid } = req.body;

  if (!uuid || !content) return res.status(400).send({ errorMessage: 'uuid and content are required' });

  try {
    const user = await Users.findOne({ where: { minecraftUUID: uuid } });

    const username = await getUsername(user);

    webhookClient.send({
      content,
      username,
      avatarURL: 'https://api.mineatar.io/face/' + uuid + '?scale=8',
    });

    res.send({ status: 'ok' });
  } catch (error) {
    console.log(error);

    res.status(500).send({ errorMessage: 'Error while sending player message' });
  }
});

router.post('/game', async (req, res) => {
  const { content, uuid } = req.body;

  if (!uuid || !content) return res.status(400).send({ errorMessage: 'uuid and content are required' });

  try {
    const messageEmbed = new EmbedBuilder()
      .setColor(process.env.EMBED_COLOR)
      .setAuthor({ name: content, iconURL: 'https://api.mineatar.io/face/' + uuid + '?scale=8' });

    webhookClient.send({
      embeds: [messageEmbed],
      username: 'Server',
    });

    res.send({ status: 'ok' });
  } catch (error) {
    console.log(error);

    res.status(500).send({ errorMessage: 'Error while sending player message' });
  }
});

module.exports = router;
