#pragma once

#include <maps/wikimap/mapspro/services/tasks_realtime/src/user_edits_metrics/lib/commit_data.h>

#include <maps/wikimap/mapspro/libs/revision/include/yandex/maps/wiki/revision/commit.h>
#include <maps/wikimap/mapspro/libs/revision_meta/include/commit_regions.h>
#include <maps/wikimap/mapspro/libs/social/include/yandex/maps/wiki/social/event.h>
#include <maps/wikimap/mapspro/libs/social/include/yandex/maps/wiki/social/gateway.h>

#include <maps/libs/chrono/include/time_point.h>
#include <maps/libs/geolib/include/polygon.h>

#include <pqxx/pqxx>

#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>

namespace maps::wiki::user_edits_metrics {

using chrono::TimePoint;
using UserIds = std::unordered_set<revision::UserID>;

class CommitLoader
{
public:
    CommitLoader(
        pqxx::transaction_base& txnCore,
        pqxx::transaction_base& txnSocial,
        pqxx::transaction_base& txnViewTrunk,
        RegionsData regionsData,
        AoiRegionsData aoiRegionsData,
        TimePoint startTime,
        std::chrono::seconds interval);

    const std::vector<CommitData>& curBatch() const { return curBatch_; }
    TimePoint curMaxTime() const { return curMaxTime_; }
    TimePoint curMinTime() const { return curMinTime_; }
    const BranchesById& branchesData() const { return branchesData_; }

    void loadNextBatch();

private:
    void addCommitData(
        const revision::Commit& commit,
        const std::unordered_map<revision::DBID, social::Event>& eventsByCommitId,
        const std::unordered_map<revision::DBID, social::Task>& tasksByCommitId,
        const std::unordered_map<revision::DBID, revision::DBIDSet>& regionsByCommitId);

    std::vector<std::string> findAoiNames(const geolib3::BoundingBox& bbox) const;

    pqxx::transaction_base& txnCore_;
    pqxx::transaction_base& txnViewTrunk_;

    revision_meta::CommitRegions commitRegions_;
    social::Gateway socialGw_;
    BranchesById branchesData_;
    RegionsData regionsData_;
    AoiRegionsData aoiRegionsData_;
    UserIds yandexUids_;

    revision::DBID curMaxCommitId_;
    std::chrono::seconds interval_;
    std::vector<CommitData> curBatch_;
    TimePoint curMaxTime_;
    TimePoint curMinTime_;
};

} // namespace maps::wiki::user_edits_metrics
