#include "../categories.h"
#include "../magic_strings.h"
#include "../attribute_dumper.h"
#include "../relation_dumper.h"



namespace maps {

namespace {
const std::string FACE_ID = "face_id";
const std::string EDGE_IDS = "edge_ids";
const std::string IS_EXCLUDED = "is_excluded";
} // namespace

struct AdSubstFcCategory: public Category {
    std::string name() const override
    {
        return category::AD_SUBST_FC;
    }

    const Table& table() const override
    {
        return table::AD_FACE_PATCH;
    }

    std::string loadRowsSqlTemplate() const override
    {
        return "WITH paged_ad_face AS (SELECT * FROM ad_face_patch WHERE face_id IN %1%) "
            "SELECT"
            " paged_ad_face.face_id " + ID + "," +
            " paged_ad_face.is_excluded " + IS_EXCLUDED + "," +
            " array_agg(face_edge.edge_id) " + EDGE_IDS + " "
            "FROM paged_ad_face "
            "LEFT JOIN face_edge ON face_edge.face_id = paged_ad_face.face_id " +
            "GROUP BY"
            " paged_ad_face.face_id,"
            " paged_ad_face.is_excluded";
    }

    void tupleToJson(
        json::ObjectBuilder& builder,
        const pqxx::row& tuple) const override
    {
        builder[jkey::ATTRIBUTES] = [&](json::ObjectBuilder builder) {
            AttributeDumper ad(name(), builder);
            ad.dumpCategory();
            ad.dump<bool>(IS_EXCLUDED, tuple);
        };

        builder[jkey::RELATIONS] = [&](json::ArrayBuilder builder) {
            RelationDumper rd(builder, tuple);
            rd.dump(relation::AD_SUBST_FC_PART, EDGE_IDS);
        };
    }
};

DEFINE_CATEGORY_OBJECT(AdSubstFc, AD_SUBST_FC);

} // namespace maps
