#include <iostream>
#include "leveldb/db.h"
#include "leveldb/options.h"
#include "gtest/gtest.h"

class RangeQueryTest : public ::testing::Test {
protected:
    leveldb::DB* db;
    leveldb::Options options;
    std::string db_path = "/tmp/range_testdb";

    void SetUp() override {
        options.create_if_missing = true;
        leveldb::Status status = leveldb::DB::Open(options, db_path, &db);
        ASSERT_TRUE(status.ok()) << "Failed to open DB: " << status.ToString();
    }

    void TearDown() override {
        delete db;
    }
};

TEST_F(RangeQueryTest, TestRangeQuery) {
    // 插入一组键值对
    std::vector<std::pair<std::string, std::string>> data = {
        {"a_key1", "value1"},
        {"a_key2", "value2"},
        {"b_key3", "value3"},
        {"b_key4", "value4"},
        {"c_key5", "value5"}
    };
    for (const auto& pair : data) {
        const std::string& key = pair.first;
        const std::string& value = pair.second;
        leveldb::Status status = db->Put(leveldb::WriteOptions(), key, value);
        ASSERT_TRUE(status.ok()) << "Failed to put data: " << status.ToString();
    }

    // 查询范围内的键值对
    std::string range_start = "a_key1";
    std::string range_end = "b_key4";
    std::vector<std::pair<std::string, std::string>> expected_data = {
        {"a_key1", "value1"},
        {"a_key2", "value2"},
        {"b_key3", "value3"},
        {"b_key4", "value4"}
    };

    leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
    it->Seek(range_start);  // 从范围起始位置开始
    std::vector<std::pair<std::string, std::string>> actual_data;
    while (it->Valid() && it->key().ToString() <= range_end) {
        actual_data.emplace_back(it->key().ToString(), it->value().ToString());
        it->Next();
    }
    delete it;

    // 验证范围查询结果是否符合预期
    ASSERT_EQ(actual_data.size(), expected_data.size()) << "Range query results size mismatch.";
    for (size_t i = 0; i < actual_data.size(); ++i) {
        EXPECT_EQ(actual_data[i].first, expected_data[i].first) << "Key mismatch at index " << i;
        EXPECT_EQ(actual_data[i].second, expected_data[i].second) << "Value mismatch at index " << i;
    }

    // 输出范围查询结果
    for (const auto& pair : actual_data) {
        const std::string& key = pair.first;
        const std::string& value = pair.second;
        std::cout << "Key: " << key << ", Value: " << value << std::endl;
    }
}

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