// Copyright 2024 gRPC authors.
//
// 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.

#include "src/core/lib/surface/call_utils.h"

#include <grpc/grpc.h>

#include <initializer_list>

#include "src/core/lib/promise/poll.h"
#include "src/core/util/upb_utils.h"
#include "src/proto/grpc/channelz/v2/promise.upb.h"
#include "src/proto/grpc/channelz/v2/property_list.upb.h"
#include "upb/mem/arena.hpp"
#include "gtest/gtest.h"

namespace grpc_core {

TEST(CallUtils, AreWriteFlagsValid) {
  EXPECT_TRUE(AreWriteFlagsValid(0));
  EXPECT_TRUE(AreWriteFlagsValid(GRPC_WRITE_BUFFER_HINT));
  EXPECT_TRUE(AreWriteFlagsValid(GRPC_WRITE_NO_COMPRESS));
  EXPECT_FALSE(AreWriteFlagsValid(0xffffffff));
}

TEST(CallUtils, AreInitialMetadataFlagsValid) {
  EXPECT_TRUE(AreInitialMetadataFlagsValid(0));
  EXPECT_TRUE(
      AreInitialMetadataFlagsValid(GRPC_INITIAL_METADATA_WAIT_FOR_READY));
  EXPECT_TRUE(AreInitialMetadataFlagsValid(GRPC_WRITE_THROUGH));
  EXPECT_FALSE(AreInitialMetadataFlagsValid(0xffffffff));
}

namespace {
template <typename... T>
std::vector<grpc_op> TestOps(T... ops) {
  std::vector<grpc_op> out;
  auto add_op = [&out](grpc_op_type type) {
    grpc_op op;
    op.op = type;
    out.push_back(op);
    return 1;
  };
  (add_op(ops), ...);
  return out;
}
}  // namespace

TEST(BatchOpIndex, Basic) {
  const auto ops = TestOps(GRPC_OP_SEND_INITIAL_METADATA, GRPC_OP_SEND_MESSAGE,
                           GRPC_OP_SEND_CLOSE_FROM_CLIENT);
  BatchOpIndex idx(ops.data(), ops.size());
  EXPECT_EQ(idx.op(GRPC_OP_SEND_INITIAL_METADATA), &ops[0]);
  EXPECT_EQ(idx.op(GRPC_OP_SEND_MESSAGE), &ops[1]);
  EXPECT_EQ(idx.op(GRPC_OP_SEND_CLOSE_FROM_CLIENT), &ops[2]);
  EXPECT_EQ(idx.op(GRPC_OP_SEND_STATUS_FROM_SERVER), nullptr);
}

TEST(CallUtils, PollBatchLoggerToProto) {
  upb::Arena arena;
  auto* proto = grpc_channelz_v2_Promise_new(arena.ptr());
  struct MockPromise {
    Poll<int> operator()() { return 1; }
    void ToProto(grpc_channelz_v2_Promise* promise_proto,
                 upb_Arena* arena) const {
      grpc_channelz_v2_Promise_set_unknown_promise(
          promise_proto, StdStringToUpbString("MockPromise"));
    }
  };
  MockPromise mock_promise_obj;
  auto logger = LogPollBatch(nullptr, mock_promise_obj);
  logger.ToProto(proto, arena.ptr());
  auto upb_to_sv = [](upb_StringView sv) -> absl::string_view {
    return absl::string_view(sv.data, sv.size);
  };
  EXPECT_EQ(upb_to_sv(grpc_channelz_v2_Promise_unknown_promise(proto)),
            "MockPromise");
}

TEST(CallUtils, OpHandlerImplToProto) {
  auto upb_to_sv = [](upb_StringView sv) -> absl::string_view {
    return absl::string_view(sv.data, sv.size);
  };
  upb::Arena arena;
  auto* proto = grpc_channelz_v2_Promise_new(arena.ptr());
  {
    auto factory = []() { return []() { return Poll<int>(1); }; };
    OpHandlerImpl<decltype(factory), GRPC_OP_SEND_MESSAGE> op_handler;
    op_handler.ToProto(proto, arena.ptr());
    auto* custom = grpc_channelz_v2_Promise_custom_promise(proto);
    EXPECT_EQ(upb_to_sv(grpc_channelz_v2_Promise_Custom_type(custom)),
              "OpHandlerImpl<SendMessage>");
    auto* properties = grpc_channelz_v2_Promise_Custom_properties(custom);
    size_t size;
    auto* entries = grpc_channelz_v2_PropertyList_properties(properties, &size);
    ASSERT_EQ(size, 1);
    ASSERT_NE(entries, nullptr);
    ASSERT_NE(entries[0], nullptr);
    EXPECT_EQ(upb_to_sv(grpc_channelz_v2_PropertyList_Element_key(entries[0])),
              "state");
    auto* value = grpc_channelz_v2_PropertyList_Element_value(entries[0]);
    ASSERT_NE(value, nullptr);
    EXPECT_EQ(upb_to_sv(grpc_channelz_v2_PropertyValue_string_value(value)),
              "dismissed");
  }
  {
    auto factory = []() { return []() { return Poll<int>(1); }; };
    OpHandlerImpl<decltype(factory), GRPC_OP_SEND_MESSAGE> op_handler(
        std::move(factory));
    op_handler.ToProto(proto, arena.ptr());
    auto* custom = grpc_channelz_v2_Promise_custom_promise(proto);
    EXPECT_EQ(upb_to_sv(grpc_channelz_v2_Promise_Custom_type(custom)),
              "OpHandlerImpl<SendMessage>");
    auto* properties = grpc_channelz_v2_Promise_Custom_properties(custom);
    size_t size;
    auto* entries = grpc_channelz_v2_PropertyList_properties(properties, &size);
    ASSERT_EQ(size, 1);
    ASSERT_NE(entries, nullptr);
    ASSERT_NE(entries[0], nullptr);
    EXPECT_EQ(upb_to_sv(grpc_channelz_v2_PropertyList_Element_key(entries[0])),
              "state");
    auto* value = grpc_channelz_v2_PropertyList_Element_value(entries[0]);
    ASSERT_NE(value, nullptr);
    EXPECT_EQ(upb_to_sv(grpc_channelz_v2_PropertyValue_string_value(value)),
              "promise_factory");
  }
}

TEST(CallUtils, WaitForCqEndOpToProto) {
  auto upb_to_sv = [](upb_StringView sv) -> absl::string_view {
    return absl::string_view(sv.data, sv.size);
  };
  upb::Arena arena;
  auto* proto = grpc_channelz_v2_Promise_new(arena.ptr());
  {
    WaitForCqEndOp op(false, nullptr, absl::OkStatus(), nullptr);
    op.ToProto(proto, arena.ptr());
    auto* custom = grpc_channelz_v2_Promise_custom_promise(proto);
    EXPECT_EQ(upb_to_sv(grpc_channelz_v2_Promise_Custom_type(custom)),
              "WaitForCqEndOp");
    auto* properties = grpc_channelz_v2_Promise_Custom_properties(custom);
    size_t size;
    auto* entries = grpc_channelz_v2_PropertyList_properties(properties, &size);
    ASSERT_EQ(size, 1);
    ASSERT_NE(entries, nullptr);
    ASSERT_NE(entries[0], nullptr);
    EXPECT_EQ(upb_to_sv(grpc_channelz_v2_PropertyList_Element_key(entries[0])),
              "state");
    auto* value = grpc_channelz_v2_PropertyList_Element_value(entries[0]);
    ASSERT_NE(value, nullptr);
    EXPECT_EQ(upb_to_sv(grpc_channelz_v2_PropertyValue_string_value(value)),
              "not_started");
  }
}

}  // namespace grpc_core

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
