#ifndef WECHATCONTEXT_H
#define WECHATCONTEXT_H

#include "Core/Singleton.h"
#include <boost/asio/steady_timer.hpp>
#include <memory>
#include <unordered_map>

class WeChatSession;

class WeChatContext : public std::enable_shared_from_this<WeChatContext> {
public:
    using OpenIds = std::vector<std::string>;

    /**
     * @brief onWechat()函数调用了此函数，对接收到的消息进行处理
     *
     * @param body
     * @return std::string  返回给微信服务器
     */
    std::string reply(const std::string &body);

protected:
    WeChatContext(boost::asio::io_context &ioContext);

    void updateAccessToken();
    OpenIds users();
    std::string broadcast(const std::string_view &message);
    void cleanExpiredSessions(const boost::system::error_code &error = boost::system::error_code());

private:
    boost::asio::io_context &m_ioContext;
    boost::asio::steady_timer m_timer;
    std::string m_accessToken;

    boost::asio::steady_timer m_sessionsExpireTimer;
    std::unordered_map<std::string, std::shared_ptr<WeChatSession>> m_sessions;

    constexpr static std::chrono::seconds sessionExpireTime{5};
    constexpr static int httpVersion = 11;
    constexpr static auto host = "api.weixin.qq.com";
    constexpr static auto port = "443";
    constexpr static auto appid = "wxdb4253b5c4259708";
    constexpr static auto secret = "199780c4d3205d8b7b1f9be3382fbf82";
};

#endif // WECHATCONTEXT_H
