#include <ChatCommand/GrantCommand/GrantCommand.hpp>

GrantCommand::GrantCommand(ServerWorld &world)
{
    require(UserPermission::GrantPerms);

    addVariant(
        "<username> <permission> - Grant a permission to a user.",
        [&world](Player &player, std::string userName, std::string permName)
        {
            auto permIt = userPermEnumByName.find(permName);
            if (permIt == userPermEnumByName.end())
            {
                player.writeChat(formatString("Unknown permission '$+'.", permName), Color::error);
                return;
            }

            UserPermission perm = permIt->second;
            if (!player.hasPermission(perm))
            {
                player.writeChat(formatString("You do not have the '$+' permission and thus can't grant it.", permName), Color::error);
                return;
            }

            if (!userDB.grantPermission(userName, perm))
            {
                player.writeChat(formatString("User '$+' does not exist.", userName), Color::error);
                return;
            }

            std::shared_ptr<Player> targetPlayer = world.getPlayer(userName);
            if (targetPlayer != nullptr)
            {
                targetPlayer->perms += perm;
            }

            player.writeChat("Permission granted.", Color::success);
        }
    );
}