const { Events } = require('discord.js');
const { Users } = require('../functions/models.js');

module.exports = {
  name: Events.MessageCreate,
  async execute(message) {
    if (message.channelId === process.env.MINECRAFT_CHANNEL_ID && !message.author.bot) {
      try {
        const user = await Users.findOne({ where: { id: message.author.id } });

        if (!user) return;

        const team = await user.getTeam();

        let tellraw;

        if (!team) {
          tellraw = `tellraw @a ["",{"text":"DC","color":"gray"},{"text":" ${user.rawUsername} > ${message.content}"}]`;
        } else {
          tellraw = `tellraw @a ["",{"text":"DC ","color":"dark_gray"},{"text":"[","color":"gray"},{"text":"${team.name}","color":"${team.color}"},{"text":"]","color":"gray"},{"text":" ${user.rawUsername} "},{"text":"> ${message.content}"}]`;
        }

        await fetch(process.env.MINECRAFT_HOST + '/console', {
          method: 'POST',
          headers: {
            'content-type': 'text/plain',
          },
          body: tellraw,
        });
      } catch (error) {
        console.error(error);
      }
    }
  },
};
