// (a AND_MAYBE "x y") OR h with get_mset(0, 1) returns doc 4 as if it matched
// the phrase "x y", which it doesn't.  The correct top document is doc 1.
//
// Build: g++ -std=c++17 selectpostlist-skip_to.cc -o selectpostlist-skip_to $(xapian-config --cxxflags --libs)
#include <xapian.h>
#include <iostream>
#include <string>
#include <vector>

static void add(Xapian::WritableDatabase& db, std::vector<std::string> words) {
    Xapian::Document doc;
    for (size_t i = 0; i < words.size(); ++i) doc.add_posting(words[i], i + 1);
    db.add_document(doc);
}

int main() {
    Xapian::WritableDatabase db(std::string(), Xapian::DB_BACKEND_INMEMORY);
    add(db, {"h"});                 // 1
    add(db, {"a"});                 // 2
    add(db, {"z"});                 // 3
    add(db, {"a", "x", "z", "y"});  // 4: has x and y, but not the phrase "x y"
    db.commit();

    std::vector<Xapian::Query> xy{Xapian::Query("x"), Xapian::Query("y")};
    Xapian::Query phrase(Xapian::Query::OP_PHRASE, xy.begin(), xy.end());
    Xapian::Query q(Xapian::Query::OP_AND_MAYBE, Xapian::Query("a"), phrase);
    q |= Xapian::Query("h");

    Xapian::Enquire enq(db);
    enq.set_query(q);
    Xapian::MSet all = enq.get_mset(0, 10);
    Xapian::MSet top = enq.get_mset(0, 1);
    std::cout << "get_mset(0, 10) top: " << *all.begin()
              << " weight " << all.begin().get_weight() << "\n";
    std::cout << "get_mset(0, 1)  top: " << *top.begin()
              << " weight " << top.begin().get_weight() << "\n";
    return *top.begin() == *all.begin() ? 0 : 1;
}
