/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *   Copyright 2020-Present 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/analytics_index_manager.hxx>
#include <couchbase/analytics_options.hxx>
#include <couchbase/bucket.hxx>
#include <couchbase/bucket_manager.hxx>
#include <couchbase/cluster_options.hxx>
#include <couchbase/diagnostics_options.hxx>
#include <couchbase/fork_event.hxx>
#include <couchbase/ping_options.hxx>
#include <couchbase/query_index_manager.hxx>
#include <couchbase/query_options.hxx>
#include <couchbase/search_index_manager.hxx>
#include <couchbase/search_options.hxx>
#include <couchbase/search_query.hxx>
#include <couchbase/search_request.hxx>
#include <couchbase/transactions.hxx>
#include <couchbase/wait_until_ready_options.hxx>

#include <chrono>
#include <memory>

namespace couchbase
{
#ifndef COUCHBASE_CXX_CLIENT_DOXYGEN
namespace core
{
class cluster;

namespace transactions
{
class transactions;
}
} // namespace core
class cluster_impl;
#endif

/**
 * The {@link cluster} is the main entry point when connecting to a Couchbase cluster.
 *
 * @since 1.0.0
 * @committed
 */
class cluster
{
public:
  /**
   * Connect to a Couchbase cluster.
   *
   * @param connection_string connection string used to locate the Couchbase cluster object.
   * @param options options to customize connection (note, that connection_string takes precedence
   * over this options).
   * @param handler the handler
   *
   * @note A connection string with the @c couchbase2:// scheme selects the @ref couchbase2
   * "couchbase2" transport, which routes every operation through a Cloud Native Gateway (CNG). It
   * requires a library built with that support and restricts how the connection string may be
   * written; see
   * @ref couchbase2.
   *
   * @since 1.0.0
   * @committed
   * @cng_since{1.4.0}
   * @cng_uncommitted
   */
  static void connect(const std::string& connection_string,
                      const cluster_options& options,
                      cluster_connect_handler&& handler);

  /**
   * Connect to a Couchbase cluster.
   *
   * @param connection_string connection string used to locate the Couchbase cluster object.
   * @param options options to customize connection (note, that connection_string takes precedence
   * over this options).
   *
   * @return future object that carries cluster object and operation status
   *
   * @note A connection string with the @c couchbase2:// scheme selects the @ref couchbase2
   * "couchbase2" transport, which routes every operation through a Cloud Native Gateway (CNG). It
   * requires a library built with that support and restricts how the connection string may be
   * written; see
   * @ref couchbase2.
   *
   * @since 1.0.0
   * @committed
   * @cng_since{1.4.0}
   * @cng_uncommitted
   */
  [[nodiscard]] static auto connect(const std::string& connection_string,
                                    const cluster_options& options)
    -> std::future<std::pair<error, cluster>>;

  cluster() = default;
  cluster(const cluster& other) = default;
  cluster(cluster&& other) = default;
  ~cluster() = default;
  auto operator=(const cluster& other) -> cluster& = default;
  auto operator=(cluster&& other) -> cluster& = default;

  /**
   * Notify the cluster of a fork-related event, so it can keep its I/O usable
   * across @c fork().
   *
   * Call it three times, in this order: @ref fork_event::prepare in the parent
   * before forking, then @ref fork_event::child in the child and @ref
   * fork_event::parent in the parent.
   *
   * NOTE: @ref fork_event::child reconnects this cluster on a fresh set of
   * sockets, because the inherited ones belong to the parent. Any @ref bucket,
   * @ref scope or @ref collection handle obtained before the fork still refers to
   * the pre-fork connections, so in the child those handles must be re-acquired
   * from the cluster -- using a stale one fails with @ref
   * errc::network::cluster_closed. Handles held in the parent stay valid.
   *
   * This function must not be called while operations are in flight on this
   * cluster from another thread.
   *
   * On platforms without @c fork(), Windows in particular, this function does
   * nothing. It remains callable everywhere so that portable code does not have to
   * guard the calls, but nothing about the cluster changes.
   *
   * @param event the fork-related event that is about to happen, or just happened.
   *
   * @throws std::system_error if the I/O backend cannot be carried across the fork.
   * There is no recovery for this: the cluster's io_context is unusable afterwards
   * and the only thing left to do with the cluster is destroy it. It is reported
   * rather than swallowed because a caller that went on using such a cluster would
   * be operating on a reactor that no longer tracks its sockets.
   *
   * @since 1.0.0
   * @uncommitted
   */
  void notify_fork(fork_event event);

  void close(std::function<void()>&& handler);
  [[nodiscard]] auto close() -> std::future<void>;

  /**
   * Replaces the current authenticator used by this cluster.
   *
   * NOTE: Setting a new authenticator does not change the authentication status of existing
   * connections.
   *
   * @param authenticator the authenticator to replace
   *
   * @return error
   *
   * @since 1.3.0
   * @committed
   */
  auto set_authenticator(const password_authenticator& authenticator) -> error;

  /**
   * Replaces the current authenticator used by this cluster.
   *
   * NOTE: Existing KV connections keep the certificate they were opened with. HTTP requests sent
   * after the call use a new connection, and a request already in flight completes.
   *
   * @param authenticator the authenticator to replace
   *
   * @exception errc::common::invalid_argument if TLS is not enabled.
   *
   * @return error
   *
   * @since 1.3.0
   * @committed
   */
  auto set_authenticator(const certificate_authenticator& authenticator) -> error;

  /**
   * Replaces the current authenticator used by this cluster.
   *
   * NOTE: Setting a new authenticator does not change the authentication status of existing
   connections.
   *
   * @param authenticator the authenticator to replace
   *
   * @return error
   *
   * @since 1.3.0
   * @uncommitted
   */
  auto set_authenticator(const jwt_authenticator& authenticator) -> error;

  /**
   * Opens a {@link bucket} with the given name.
   *
   * @param bucket_name the name of the bucket to open.
   * @return a {@link bucket} once opened.
   *
   * @since 1.0.0
   * @committed
   */
  [[nodiscard]] auto bucket(std::string_view bucket_name) const -> bucket;

  /**
   * Performs a query against the query (N1QL) services.
   *
   * @param statement the N1QL query statement.
   * @param options options to customize the query request.
   * @param handler the handler that implements @ref query_handler
   *
   * @exception errc::common::ambiguous_timeout
   * @exception errc::common::unambiguous_timeout
   *
   * @since 1.0.0
   * @committed
   */
  void query(std::string statement, const query_options& options, query_handler&& handler) const;

  /**
   * Performs a query against the query (N1QL) services.
   *
   * @param statement the N1QL query statement.
   * @param options options to customize the query request.
   * @return future object that carries result of the operation
   *
   * @since 1.0.0
   * @committed
   */
  [[nodiscard]] auto query(std::string statement, const query_options& options) const
    -> std::future<std::pair<error, query_result>>;

  /**
   * Performs a streaming query against the query (N1QL) services.
   *
   * The handler resolves as soon as the response preamble has been parsed; rows are then pulled
   * lazily from the @ref query_stream_result, so the full result is never buffered in memory.
   *
   * @note Prepared statements (@ref query_options#adhoc set to false) are not streamed: such a
   * request falls back to the buffered @ref query() path and its rows are replayed through the
   * returned handle.
   *
   * The handler runs on the library's I/O thread, so the stream must be drained with the callback
   * @ref query_stream_result#next() overload rather than the blocking ones:
   *
   * @snippet{trimleft} test_integration_examples_streaming.cxx example-query-stream-async
   *
   * @param statement the N1QL query statement.
   * @param options options to customize the query request.
   * @param handler the handler that implements @ref query_stream_handler
   *
   * @since 1.4.0
   * @volatile
   */
  void query_stream(std::string statement,
                    const query_options& options,
                    query_stream_handler&& handler) const;

  /**
   * Performs a streaming query against the query (N1QL) services.
   *
   * Rows are pulled from the returned handle one at a time, so a result of any size costs the same
   * bounded amount of memory:
   *
   * @snippet{trimleft} test_integration_examples_streaming.cxx example-query-stream
   *
   * The document type the rows are decoded into:
   *
   * @snippet{trimleft} test_integration_examples_streaming.cxx streaming-product
   *
   * A failure surfaces either here, before the stream starts, or as the terminal of
   * @ref query_stream_result#next() — possibly after rows have already been consumed, which a
   * buffered @ref query() cannot produce. Both channels have to be handled:
   *
   * @snippet{trimleft} test_integration_examples_streaming.cxx example-query-stream-errors
   *
   * @param statement the N1QL query statement.
   * @param options options to customize the query request.
   * @return future object that carries the streaming result handle
   *
   * @since 1.4.0
   * @volatile
   */
  [[nodiscard]] auto query_stream(std::string statement, const query_options& options = {}) const
    -> std::future<std::pair<error, query_stream_result>>;

  /**
   * Performs a request against the full text search services.
   *
   * This can be used to perform a traditional FTS query, and/or a vector search.
   *
   * @param index_name name of the search index
   * @param request request object, see @ref search_request for more details.
   * @param options options to customize the query request.
   * @param handler the handler that implements @ref search_handler
   *
   * @exception errc::common::ambiguous_timeout
   * @exception errc::common::unambiguous_timeout
   *
   * @see https://docs.couchbase.com/server/current/fts/fts-introduction.html
   *
   * @since 1.0.0
   * @committed
   */
  void search(std::string index_name,
              search_request request,
              const search_options& options,
              search_handler&& handler) const;

  /**
   * Performs a request against the full text search services.
   *
   * This can be used to perform a traditional FTS query, and/or a vector search.
   *
   * @param index_name name of the search index
   * @param request request object, see @ref search_request for more details.
   * @param options options to customize the query request.
   * @return future object that carries result of the operation
   *
   * @exception errc::common::ambiguous_timeout
   * @exception errc::common::unambiguous_timeout
   *
   * @see https://docs.couchbase.com/server/current/fts/fts-introduction.html
   *
   * @since 1.0.0
   * @committed
   */
  [[nodiscard]] auto search(std::string index_name,
                            search_request request,
                            const search_options& options = {}) const
    -> std::future<std::pair<error, search_result>>;

  /**
   * Performs a query against the analytics services.
   *
   * @param statement the query statement.
   * @param options options to customize the query request.
   * @param handler the handler that implements @ref query_handler
   *
   * @exception errc::common::ambiguous_timeout
   * @exception errc::common::unambiguous_timeout
   *
   * @see https://docs.couchbase.com/server/current/analytics/introduction.html
   *
   * @since 1.0.0
   * @committed
   */
  void analytics_query(std::string statement,
                       const analytics_options& options,
                       analytics_handler&& handler) const;

  /**
   * Performs a query against the analytics services.
   *
   * @param statement the query statement.
   * @param options options to customize the query request.
   * @return future object that carries result of the operation
   *
   * @see https://docs.couchbase.com/server/current/analytics/introduction.html
   *
   * @since 1.0.0
   * @committed
   */
  [[nodiscard]] auto analytics_query(std::string statement,
                                     const analytics_options& options = {}) const
    -> std::future<std::pair<error, analytics_result>>;

  /**
   * Performs a streaming query against the analytics services.
   *
   * The handler resolves as soon as the response preamble has been parsed; rows are then pulled
   * lazily from the @ref analytics_stream_result, so the full result is never buffered in memory.
   *
   * The handler runs on the library's I/O thread, so the stream must be drained with the callback
   * @ref analytics_stream_result#next() overload rather than the blocking ones. The query
   * equivalent shows the pattern:
   *
   * @snippet{trimleft} test_integration_examples_streaming.cxx example-query-stream-async
   *
   * @param statement the analytics query statement.
   * @param options options to customize the query request.
   * @param handler the handler that implements @ref analytics_stream_handler
   *
   * @since 1.4.0
   * @volatile
   */
  void analytics_query_stream(std::string statement,
                              const analytics_options& options,
                              analytics_stream_handler&& handler) const;

  /**
   * Performs a streaming query against the analytics services.
   *
   * @snippet{trimleft} test_integration_examples_streaming.cxx example-analytics-stream
   *
   * @param statement the analytics query statement.
   * @param options options to customize the query request.
   * @return future object that carries the streaming result handle
   *
   * @since 1.4.0
   * @volatile
   */
  [[nodiscard]] auto analytics_query_stream(std::string statement,
                                            const analytics_options& options = {}) const
    -> std::future<std::pair<error, analytics_stream_result>>;

  /**
   * Performs application-level ping requests against services in the Couchbase cluster.
   *
   * @note This operation performs active I/O against services and endpoints to assess their health.
   * If you do not wish to performs I/O, consider using @ref diagnostics() instead.
   *
   * @param options custom options to change the default behavior.
   * @param handler the handler that implements @ref ping_handler.
   *
   * @note Not served over the @ref couchbase2 "couchbase2" transport, which has no per-node service
   * endpoints to probe and reports @ref errc::common::feature_not_available instead.
   *
   * @since 1.0.0
   * @committed
   * @cng_since{1.4.0}
   * @cng_uncommitted
   */
  void ping(const ping_options& options, ping_handler&& handler) const;

  /**
   * Performs application-level ping requests against services in the Couchbase cluster.
   *
   * @note This operation performs active I/O against services and endpoints to assess their health.
   * If you do not wish to performs I/O, consider using @ref diagnostics() instead.
   *
   * @param options custom options to change the default behavior.
   * @return future object that carries result of the operation.
   *
   * @note Not served over the @ref couchbase2 "couchbase2" transport, which has no per-node service
   * endpoints to probe and reports @ref errc::common::feature_not_available instead.
   *
   * @since 1.0.0
   * @committed
   * @cng_since{1.4.0}
   * @cng_uncommitted
   */
  [[nodiscard]] auto ping(const ping_options& options = {}) const
    -> std::future<std::pair<error, ping_result>>;

  /**
   * Assembles a diagnostics report on the current state of the cluster from the SDK's point of
   * view.
   *
   * @note This operation does not perform any I/O to produce the report. It will only use the
   * current known state of the cluster to assemble the report So, if for example, no SQL++ queries
   * have been run, the Query service's socket pool might be empty and as a result not show up in
   * the report. If you wish to actively assess the health of the cluster by performing I/O,
   * consider using @ref ping() instead.
   *
   * @param options custom options to change the default behavior.
   * @param handler the handler that implements @ref diagnostics_handler.
   *
   * @note Not served over the @ref couchbase2 "couchbase2" transport, which keeps no per-node
   * connection state to report on and returns @ref errc::common::feature_not_available rather than
   * an empty report.
   *
   * @since 1.0.0
   * @committed
   * @cng_since{1.4.0}
   * @cng_uncommitted
   */
  void diagnostics(const diagnostics_options& options, diagnostics_handler&& handler) const;

  /**
   * Assembles a diagnostics report on the current state of the cluster from the SDK's point of
   * view.
   *
   * @note This operation does not perform any I/O to produce the report. It will only use the
   * current known state of the cluster to assemble the report So, if for example, no SQL++ queries
   * have been run, the Query service's socket pool might be empty and as a result not show up in
   * the report. If you wish to actively assess the health of the cluster by performing I/O,
   * consider using @ref ping() instead.
   *
   * @param options custom options to change the default behavior.
   * @return future object that carries result of the operation.
   *
   * @note Not served over the @ref couchbase2 "couchbase2" transport, which keeps no per-node
   * connection state to report on and returns @ref errc::common::feature_not_available rather than
   * an empty report.
   *
   * @since 1.0.0
   * @committed
   * @cng_since{1.4.0}
   * @cng_uncommitted
   */
  [[nodiscard]] auto diagnostics(const diagnostics_options& options = {}) const
    -> std::future<std::pair<error, diagnostics_result>>;

  /**
   * Waits until the desired state of the cluster is reached, actively pinging its services until
   * they respond or the timeout elapses.
   *
   * Over couchbase2, the wait ends once the gRPC channel to the gateway is connected. No service is
   * pinged, the requested services are not considered, and @c cluster_state::online and
   * @c cluster_state::degraded are the same state.
   *
   * Closing the cluster ends a wait in flight with @ref errc::network::cluster_closed, and a wait
   * started after the cluster is closed fails the same way.
   *
   * @param timeout the maximum time to wait for readiness.
   * @param options custom options to change the default behavior.
   * @param handler the handler that implements @ref wait_until_ready_handler.
   *
   * @since 1.4.0
   * @committed
   */
  void wait_until_ready(std::chrono::milliseconds timeout,
                        const wait_until_ready_options& options,
                        wait_until_ready_handler&& handler) const;

  /**
   * Waits until the desired state of the cluster is reached, actively pinging its services until
   * they respond or the timeout elapses.
   *
   * Over couchbase2, the wait ends once the gRPC channel to the gateway is connected. No service is
   * pinged, the requested services are not considered, and @c cluster_state::online and
   * @c cluster_state::degraded are the same state.
   *
   * Closing the cluster ends a wait in flight with @ref errc::network::cluster_closed, and a wait
   * started after the cluster is closed fails the same way.
   *
   * @param timeout the maximum time to wait for readiness.
   * @param options custom options to change the default behavior.
   * @return future object that carries result of the operation.
   *
   * @since 1.4.0
   * @committed
   */
  [[nodiscard]] auto wait_until_ready(std::chrono::milliseconds timeout,
                                      const wait_until_ready_options& options = {}) const
    -> std::future<error>;

  /**
   * Provides access to the N1QL index management services.
   *
   * @return a manager instance
   *
   * @since 1.0.0
   * @committed
   */
  [[nodiscard]] auto query_indexes() const -> query_index_manager;

  /**
   * Provides access ot the Analytics index management services.
   *
   * @return a manager instance
   *
   * @since 1.0.0
   * @committed
   */
  [[nodiscard]] auto analytics_indexes() const -> analytics_index_manager;

  /**
   * Provides access to the bucket management services.
   *
   * @return a manager instance
   *
   * @since 1.0.0
   * @committed
   */
  [[nodiscard]] auto buckets() const -> bucket_manager;

  /**
   * Provides access to search index management services
   *
   * @return a manager instance
   *
   * @since 1.0.0
   * @committed
   */
  [[nodiscard]] auto search_indexes() const -> search_index_manager;

  /**
   * Provides access to transaction services.
   *
   * See {@link transactions} for details on using the transactions object.
   *
   * @return an {@link transactions} object
   *
   * @since 1.0.0
   * @committed
   */
  [[nodiscard]] auto transactions() const -> std::shared_ptr<couchbase::transactions::transactions>;

private:
#ifndef COUCHBASE_CXX_CLIENT_DOXYGEN
  friend class cluster_impl;
  explicit cluster(std::shared_ptr<cluster_impl> impl);
#endif

  std::shared_ptr<cluster_impl> impl_{};
};
} // namespace couchbase
