#include <maps/wikimap/mapspro/libs/views/include/regions.h>

#include <maps/libs/geolib/include/polygon.h>
#include <maps/libs/geolib/include/serialization.h>

namespace maps::wiki::views::trunk {

using namespace std::literals;

revision::DBIDSet
getRegions(pqxx::transaction_base& txnViewTrunk, const geolib3::BoundingBox& bbox)
{
    const auto bboxEwkb = txnViewTrunk.esc_raw(
        geolib3::EWKB::toString<geolib3::SpatialReference::Epsg3395>(bbox.polygon())
    );

    const auto query =
        "WITH sattrs_keys AS (\n"s
        "    SELECT DISTINCT SKEYS(service_attrs) sattr\n"
        "    FROM vrevisions_trunk.contour_objects_geom\n"
        "    WHERE\n"
        "        ST_Intersects(\n"
        "          the_geom,\n"
        "          ST_GeomFromEWKB('" + bboxEwkb + "')\n"
        "        )\n"
        "        AND service_attrs ? 'srv:is_part_of_region'\n"
        "        AND domain_attrs -> 'cat:ad' = '1'\n" // instead of very slow domain_attrs ? 'cat:ad'
        ")\n"
        "SELECT SUBSTR(sattr, 23)\n"
        "FROM sattrs_keys\n"
        "WHERE sattr LIKE 'srv:is_part_of_region_%'\n";

    revision::DBIDSet result;
    for (const auto& row: txnViewTrunk.exec(query)) {
        result.emplace(row[0].as<revision::DBID>());
    }
    return result;
}

} // namespace maps::wiki::views::trunk
