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

class LevelDBTest : public ::testing::Test {
protected:
    leveldb::DB* db;
    leveldb::Options options;
    std::string db_path = "/tmp/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(LevelDBTest, CompactionTest) {
    // 插入数据
    db->Put(leveldb::WriteOptions(), "start", "value1");
    db->Put(leveldb::WriteOptions(), "end", "value2");
    db->Put(leveldb::WriteOptions(), "key_to_delete", "value3");

    // 删除一个键，模拟删除标记
    db->Delete(leveldb::WriteOptions(), "key_to_delete");

    // 触发压缩
    leveldb::Slice begin_key("start");
    leveldb::Slice end_key("end");
    db->CompactRange(&begin_key, &end_key);

    // 验证压缩后的数据
    std::string value;
    leveldb::Status status = db->Get(leveldb::ReadOptions(), "key_to_delete", &value);
    if (!status.ok()) {
        std::cout << "'key_to_delete' was successfully removed during compaction." << std::endl;
    } else {
        FAIL() << "Unexpected: 'key_to_delete' still exists: " << value;
    }
}

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