/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *   Copyright 2024. Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
#pragma once

#include <couchbase/error_codes.hxx>

#include "core/io/stream_deadline.hxx"
#include "core/utils/movable_function.hxx"

#include <asio/steady_timer.hpp>

#include <cstddef>
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <system_error>

namespace couchbase::core::io
{

class http_session;
struct http_streaming_parser;
class http_streaming_response_body_impl;

class http_streaming_response_body
{
public:
  http_streaming_response_body() = default;
  http_streaming_response_body(asio::io_context& io,
                               std::shared_ptr<http_session> session,
                               std::string cached_data = {},
                               bool reading_complete = false,
                               std::size_t cached_chunk_size = 0);

  // Closes the body with `on_expiry` at `deadline_tp`, whether or not a read is in flight. A
  // deadline already in the past fires as soon as the io_context runs it. Re-arming before expiry
  // replaces the previous deadline. Once the body has ended, by expiry or otherwise, a further
  // call arms nothing and reports body_already_ended.
  //
  // Callable from any thread. Arming, cancelling and the terminal transition share one lock. An
  // expiry already queued when that lock is taken is superseded, not delivered.
  [[nodiscard]] auto set_deadline(std::chrono::time_point<std::chrono::steady_clock> deadline_tp,
                                  deadline_terminal on_expiry) -> deadline_state;
  // Supersedes an armed deadline without ending the body, under the same lock as set_deadline.
  // For a caller that must post its own teardown: stopping the deadline here first keeps a cancel
  // from losing to an expiry that lands before the posted work runs.
  void cancel_deadline();
  // Delivers the next body chunk. The bool argument is `has_more`: true while the response is
  // still in progress (an empty chunk with has_more==true simply carried no body bytes, e.g. a
  // read consumed by HTTP chunk framing), false once the stream has ended. Consumers must key
  // end-of-stream off this flag, never off an empty data string.
  //
  // The error_code next() reports is the reason the body was closed, not the error the read
  // returned: read_some reports request_canceled for every aborted read.
  void next(utils::movable_function<void(std::string, bool, std::error_code)>&& callback);
  void close(std::error_code ec = couchbase::errc::common::request_canceled);

private:
  std::shared_ptr<http_streaming_response_body_impl> impl_;
};

class http_streaming_response_impl;

// Where a streaming response was dispatched, captured at construction rather than held as a session
// reference: an error context is built after the stream has been torn down, by which point the
// session may already be back in the keep-alive pool or gone.
struct http_dispatch_info {
  std::string hostname{};
  std::uint16_t port{};
  std::string remote_address{};
  std::string local_address{};
};

class http_streaming_response
{
public:
  http_streaming_response() = default;
  http_streaming_response(asio::io_context& io,
                          const http_streaming_parser& parser,
                          std::shared_ptr<http_session> session);

  [[nodiscard]] auto status_code() const -> const std::uint32_t&;
  [[nodiscard]] auto status_message() const -> const std::string&;
  [[nodiscard]] auto headers() const -> const std::map<std::string, std::string>&;
  [[nodiscard]] auto body() -> http_streaming_response_body&;
  [[nodiscard]] auto must_close_connection() const -> bool;
  [[nodiscard]] auto dispatch_info() const -> const http_dispatch_info&;

private:
  std::shared_ptr<http_streaming_response_impl> impl_;
};
} // namespace couchbase::core::io
