#ifndef SERVICELOGIC_INL
#define SERVICELOGIC_INL

#include "Core/Logger.h"
#include "WeChat/OfficialAccount/Context.h"
#include <boost/beast/http/empty_body.hpp>
#include <boost/beast/http/file_body.hpp>
#include <boost/json/parse.hpp>
#include <boost/json/serialize.hpp>
#include <boost/nowide/fstream.hpp>
#include <boost/url.hpp>
#include <filesystem>

namespace ServiceLogic {

template <class Send>
static void onWechat(const Older::Application::Pointer &app, const StringRequest &request, Send &&send) {
    using namespace boost::beast;
    boost::urls::url url(request.target());
    auto context = Core::Singleton<WeChatContext>::instance();
    http::response<boost::beast::http::string_body> response;
    if (request.count("Content-Type") > 0 && request.at("Content-Type") == "text/xml") {
        response.body() = context->reply(request.body());
    } else {
        auto query = url.params();
        if (auto iterator = query.find("echostr"); iterator != query.end()) {
            response.body() = (*iterator)->value;
        }
    }
    boost::beast::error_code ec;

    response.set(http::field::server, BOOST_BEAST_VERSION_STRING);
    response.set(http::field::content_type, "text/xml;charset=UTF-8");
    response.keep_alive(request.keep_alive());

    response.prepare_payload();
    return send(std::move(response));
}
} // namespace ServiceLogic

#endif // SERVICELOGIC_INL
