#include "building.h"

#include <maps/libs/geolib/include/serialization.h>
#include <yandex/maps/wiki/revision/revisionsgateway.h>
#include <yandex/maps/wiki/revision/snapshot.h>

namespace maps::wiki::schedule_feedback {

namespace rf = revision::filters;

std::vector<geolib3::Polygon2> revisionBuildingsGeom(
    const geolib3::BoundingBox& bboxMerc,
    pqxx::transaction_base& coreTxn)
{
    revision::RevisionsGateway gtw(coreTxn);
    auto snapshot = gtw.snapshot(gtw.maxSnapshotId());

    rf::ProxyFilterExpr buildingFilter =
        rf::ObjRevAttr::isNotDeleted() &&
        rf::ObjRevAttr::isNotRelation() &&
        rf::Attr("cat:bld").defined() &&
        rf::Geom::defined();

    auto areaFilter = rf::GeomFilterExpr(
        rf::GeomFilterExpr::Operation::IntersectsPolygons,
        bboxMerc.minX(), bboxMerc.minY(),
        bboxMerc.maxX(), bboxMerc.maxY());

    auto filter = buildingFilter && areaFilter;
    auto buildings = snapshot.objectRevisionsByFilter(filter);

    std::vector<geolib3::Polygon2> geoms;
    for (const auto& rev : buildings) {
        ASSERT(rev.data().geometry);
        const auto& geom = *rev.data().geometry;
        geoms.push_back(geolib3::WKB::read<geolib3::Polygon2>(geom));
    }

    return geoms;
}

} // namespace maps::wiki::schedule_feedback
