const applyUsername = async (user, member) => {
  await user.reload();

  let rawUsername = member.user.globalName;

  if (user.useMinecraftUsername && user.minecraftUuid) {
    const response = await fetch(`https://sessionserver.mojang.com/session/minecraft/profile/${user.minecraftUuid}`);
    const minecraftProfile = await response.json();

    rawUsername = minecraftProfile.name;
  }

  user.rawUsername = rawUsername;

  const username = await getUsername(user);

  await user.save();
  await member.setNickname(username.slice(0, 32));

  return username;
};

const getUsername = async (user) => {
  const team = await user.getTeam();

  return team ? user.rawUsername + ' [' + team.name + ']' : user.rawUsername;
};

module.exports = { applyUsername, getUsername };
