#include <ChatCommand/RevokeCommand/RevokeCommand.hpp>

RevokeCommand::RevokeCommand(ServerWorld &world)
{
    require(UserPermission::RevokePerms);

    addVariant(
        "<username> <permission> - Remove a permission from a user.",
        [&world](Player &player, std::string userName, std::string permName)
        {
            if (userName == player.getName())
            {
                player.writeChat("You cannot revoke permissions from yourself.", Color::error);
                return;
            }

            auto permIt = userPermEnumByName.find(permName);
            if (permIt == userPermEnumByName.end())
            {
                player.writeChat(formatString("Unknown permission '$+'.", permName), Color::error);
                return;
            }

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

                return;
            }

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

            auto targetPlayer = world.getPlayer(userName);
            if (targetPlayer != nullptr)
            {
                targetPlayer->perms -= perm;
            }

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