//------------------------------------------------------------------------------
/*
    This file is part of clio: https://github.com/XRPLF/clio
    Copyright (c) 2023, the clio developers.

    Permission to use, copy, modify, and distribute this software for any
    purpose with or without fee is hereby granted, provided that the above
    copyright notice and this permission notice appear in all copies.

    THE  SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF
    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY  SPECIAL,  DIRECT,  INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================

#include "rpc/handlers/NoRippleCheck.hpp"

#include "rpc/Errors.hpp"
#include "rpc/JS.hpp"
#include "rpc/RPCHelpers.hpp"
#include "rpc/common/JsonBool.hpp"
#include "rpc/common/Types.hpp"
#include "util/Assert.hpp"
#include "util/JsonUtils.hpp"

#include <boost/json/array.hpp>
#include <boost/json/conversion.hpp>
#include <boost/json/object.hpp>
#include <boost/json/value.hpp>
#include <boost/json/value_to.hpp>
#include <fmt/format.h>
#include <xrpl/basics/strHex.h>
#include <xrpl/protocol/AccountID.h>
#include <xrpl/protocol/Indexes.h>
#include <xrpl/protocol/LedgerFormats.h>
#include <xrpl/protocol/LedgerHeader.h>
#include <xrpl/protocol/SField.h>
#include <xrpl/protocol/STAmount.h>
#include <xrpl/protocol/STBase.h>
#include <xrpl/protocol/STLedgerEntry.h>
#include <xrpl/protocol/Serializer.h>
#include <xrpl/protocol/TxFlags.h>
#include <xrpl/protocol/UintTypes.h>
#include <xrpl/protocol/jss.h>

#include <cstdint>
#include <limits>
#include <optional>
#include <string>
#include <utility>

namespace rpc {

NoRippleCheckHandler::Result
NoRippleCheckHandler::process(NoRippleCheckHandler::Input const& input, Context const& ctx) const
{
    auto const range = sharedPtrBackend_->fetchLedgerRange();
    ASSERT(range.has_value(), "NoRippleCheck's ledger range must be available");

    auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq(
        *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence
    );

    if (!expectedLgrInfo.has_value())
        return Error{expectedLgrInfo.error()};

    auto const& lgrInfo = expectedLgrInfo.value();
    auto const accountID = accountFromStringStrict(input.account);
    auto const keylet = ripple::keylet::account(*accountID).key;
    auto const accountObj = sharedPtrBackend_->fetchLedgerObject(keylet, lgrInfo.seq, ctx.yield);

    if (!accountObj)
        return Error{Status{RippledError::rpcACT_NOT_FOUND, "accountNotFound"}};

    auto it = ripple::SerialIter{accountObj->data(), accountObj->size()};
    auto sle = ripple::SLE{it, keylet};
    auto accountSeq = sle.getFieldU32(ripple::sfSequence);
    bool const bDefaultRipple = (sle.getFieldU32(ripple::sfFlags) & ripple::lsfDefaultRipple) != 0u;
    auto const fees = input.transactions ? sharedPtrBackend_->fetchFees(lgrInfo.seq, ctx.yield) : std::nullopt;

    auto output = NoRippleCheckHandler::Output();

    if (input.transactions)
        output.transactions.emplace(boost::json::array());

    auto const getBaseTx = [&](ripple::AccountID const& accountID, std::uint32_t accountSeq) {
        boost::json::object tx;
        tx[JS(Sequence)] = accountSeq;
        tx[JS(Account)] = ripple::toBase58(accountID);
        tx[JS(Fee)] = toBoostJson(fees->base.jsonClipped());

        return tx;
    };

    if (bDefaultRipple && !input.roleGateway) {
        output.problems.emplace_back(
            "You appear to have set your default ripple flag even though you are not a gateway. This is not "
            "recommended unless you are experimenting"
        );
    } else if (input.roleGateway && !bDefaultRipple) {
        output.problems.emplace_back("You should immediately set your default ripple flag");

        if (input.transactions) {
            auto tx = getBaseTx(*accountID, accountSeq++);
            tx[JS(TransactionType)] = "AccountSet";
            tx[JS(SetFlag)] = ripple::asfDefaultRipple;
            output.transactions->push_back(tx);
        }
    }

    auto limit = input.limit;

    traverseOwnedNodes(
        *sharedPtrBackend_,
        *accountID,
        lgrInfo.seq,
        std::numeric_limits<std::uint32_t>::max(),
        {},
        ctx.yield,
        [&](ripple::SLE const ownedItem) {
            // don't push to result if limit is reached
            if (limit != 0 && ownedItem.getType() == ripple::ltRIPPLE_STATE) {
                bool const bLow = accountID == ownedItem.getFieldAmount(ripple::sfLowLimit).getIssuer();

                bool const bNoRipple = (ownedItem.getFieldU32(ripple::sfFlags) &
                                        (bLow ? ripple::lsfLowNoRipple : ripple::lsfHighNoRipple)) != 0u;

                std::string problem;
                bool needFix = false;
                if (bNoRipple && input.roleGateway) {
                    problem = "You should clear the no ripple flag on your ";
                    needFix = true;
                } else if (!bNoRipple && !input.roleGateway) {
                    problem = "You should probably set the no ripple flag on your ";
                    needFix = true;
                }
                if (needFix) {
                    --limit;

                    ripple::AccountID const peer =
                        ownedItem.getFieldAmount(bLow ? ripple::sfHighLimit : ripple::sfLowLimit).getIssuer();
                    ripple::STAmount const peerLimit =
                        ownedItem.getFieldAmount(bLow ? ripple::sfHighLimit : ripple::sfLowLimit);

                    problem += fmt::format(
                        "{} line to {}", to_string(peerLimit.getCurrency()), to_string(peerLimit.getIssuer())
                    );
                    output.problems.emplace_back(problem);

                    if (input.transactions) {
                        ripple::STAmount limitAmount(
                            ownedItem.getFieldAmount(bLow ? ripple::sfLowLimit : ripple::sfHighLimit)
                        );
                        limitAmount.setIssuer(peer);

                        auto tx = getBaseTx(*accountID, accountSeq++);

                        tx[JS(TransactionType)] = "TrustSet";
                        tx[JS(LimitAmount)] = toBoostJson(limitAmount.getJson(ripple::JsonOptions::none));
                        tx[JS(Flags)] = bNoRipple ? ripple::tfClearNoRipple : ripple::tfSetNoRipple;

                        output.transactions->push_back(tx);
                    }
                }
            }

            return true;
        }
    );

    output.ledgerIndex = lgrInfo.seq;
    output.ledgerHash = ripple::strHex(lgrInfo.hash);

    return output;
}

NoRippleCheckHandler::Input
tag_invoke(boost::json::value_to_tag<NoRippleCheckHandler::Input>, boost::json::value const& jv)
{
    auto input = NoRippleCheckHandler::Input{};
    auto const& jsonObject = jv.as_object();

    input.account = boost::json::value_to<std::string>(jsonObject.at(JS(account)));
    input.roleGateway = jsonObject.at(JS(role)).as_string() == "gateway";

    if (jsonObject.contains(JS(limit)))
        input.limit = util::integralValueAs<uint32_t>(jsonObject.at(JS(limit)));

    if (jsonObject.contains(JS(transactions)))
        input.transactions = boost::json::value_to<JsonBool>(jsonObject.at(JS(transactions)));

    if (jsonObject.contains(JS(ledger_hash)))
        input.ledgerHash = boost::json::value_to<std::string>(jsonObject.at(JS(ledger_hash)));

    if (jsonObject.contains(JS(ledger_index))) {
        auto const expectedLedgerIndex = util::getLedgerIndex(jsonObject.at(JS(ledger_index)));
        if (expectedLedgerIndex.has_value())
            input.ledgerIndex = *expectedLedgerIndex;
    }

    return input;
}

void
tag_invoke(boost::json::value_from_tag, boost::json::value& jv, NoRippleCheckHandler::Output const& output)
{
    using boost::json::value_from;

    auto obj = boost::json::object{
        {JS(ledger_hash), output.ledgerHash},
        {JS(ledger_index), output.ledgerIndex},
        {"problems", value_from(output.problems)},
        {JS(validated), output.validated},
    };

    if (output.transactions)
        obj.emplace(JS(transactions), *(output.transactions));

    jv = std::move(obj);
}

}  // namespace rpc
