#pragma once

#include "mrc_pedestrian_region.h"
#include "ugc_backoffice_client.h"

#include <yandex/maps/wiki/revision/commit.h>
#include <yandex/maps/wiki/revision/diff.h>
#include <yandex/maps/wiki/revision/revisionid.h>

#include <maps/libs/pgpool/include/pgpool3.h>

#include <map>
#include <set>
#include <unordered_map>

namespace maps::wiki::tasks::mrc_pedestrian {

constexpr size_t PUBSUB_CONSUMER_BATCH_SIZE = 1000;

class TasksGenerator
{
public:
    TasksGenerator(
        pgpool3::Pool& pool,
        UgcBackofficeClient ugcBackofficeClient);

    size_t consumeNewCommits();

private:
    void onRegionCreated(
        const MrcPedestrianRegion& region,
        revision::DBID objectId,
        const revision::Commit& commit,
        const revision::AttributesDiff& attrsDiff);

    void onRegionDeleted(
        const MrcPedestrianRegion& region,
        revision::DBID objectId,
        const revision::Commit& commit);

    void onRegionAttrsChanged(
        MrcPedestrianRegion& region,
        revision::DBID objectId,
        const revision::Commit& commit,
        const revision::AttributesDiff& attrsDiff);

    void createTaskFor(const MrcPedestrianRegion& region);

    void deleteTaskFor(revision::DBID objectId, const std::string& uid);

    static std::map<revision::DBID, std::set<revision::DBID>>
    loadCommitIdToObjectIdsMap(
        pqxx::transaction_base& txn,
        const std::vector<revision::DBID>& commitIds);

    static std::map<revision::DBID, revision::Commit>
    loadCommitIdToCommitMap(
        pqxx::transaction_base& txn,
        const std::vector<revision::DBID>& commitIds);

    void consumeCommit(
        pqxx::transaction_base& txn,
        const revision::Commit& commit,
        const std::set<revision::DBID>& objectIds);

    static std::unordered_map<revision::DBID, MrcPedestrianRegion>
    loadRegions(
        pqxx::transaction_base& txn,
        revision::DBID commitId,
        const std::set<revision::DBID>& objectIds);

private:
    pgpool3::Pool& pool_;
    UgcBackofficeClient ugcBackofficeClient_;
};

} // namespace maps::wiki::tasks::mrc_pedestrian
