#ifndef HTTPSESSION_H
#define HTTPSESSION_H

#include "SharedState.h"
#include "boost/beast.hpp"
#include <cstdlib>
#include <memory>
#include <optional>

/** Represents an established HTTP connection
 */
class HttpSession : public std::enable_shared_from_this<HttpSession> {
    void doRead();
    void onRead(boost::beast::error_code ec, std::size_t);
    void onWrite(boost::beast::error_code ec, std::size_t, bool close);

    //    void sendResponse(boost::beast::http::response<boost::beast::http::string_body> &&response);

public:
    using Request = boost::beast::http::request<boost::beast::http::string_body>;
    HttpSession(boost::asio::ip::tcp::socket &&socket, std::shared_ptr<SharedState> const &state);
    template <typename Response>
    void reply(Response &&response) {
        using ResponseType = typename std::decay_t<decltype(response)>;
        auto sp = std::make_shared<ResponseType>(std::forward<decltype(response)>(response));
        boost::beast::http::async_write(
            m_stream, *sp, [self = shared_from_this(), sp](boost::beast::error_code ec, std::size_t bytes) {
                self->onWrite(ec, bytes, sp->need_eof());
            });
    }
    void errorReply(const Request &request, boost::beast::http::status status, boost::beast::string_view message);

    void run();

private:
    boost::beast::tcp_stream m_stream;
    boost::beast::flat_buffer m_buffer{std::numeric_limits<std::uint32_t>::max()};
    SharedStatePtr m_state;
    std::optional<boost::beast::http::request_parser<boost::beast::http::string_body>> m_parser;
};

#endif // HTTPSESSION_H
