#include "export.h"

#include <yandex/maps/wiki/mds_dataset/dataset_gateway.h>
#include <yandex/maps/wiki/mds_dataset/export_metadata.h>

using namespace std::string_literals;
namespace md = maps::wiki::mds_dataset;

namespace maps {
namespace wiki {

namespace {

const auto SELECT_EXPORT_RESULT_QUERY =
    "SELECT branch_id, dataset_id"
    "  FROM service.export_task"
    "  JOIN service.export_result ON (id = task_id)"
    "  WHERE subset='domain' AND dataset_id IS NOT NULL"
    "    AND branch_id IN ("
    "      SELECT DISTINCT branch_id FROM service.export_task"
    "      ORDER BY 1 DESC LIMIT 1)"s;

} // namespace

EventsHolder loadBranchExportedTimes(pqxx::transaction_base& coreTxn)
{
    EventsHolder eventsHolder;

    for (const auto& row: coreTxn.exec(SELECT_EXPORT_RESULT_QUERY)) {
        auto branchId = row[0].as<BranchId>();
        auto datasetId = row[1].as<std::string>();

        md::ExportMetadata::FilterType filter(coreTxn);
        filter.byId(datasetId);
        filter.byStatus(md::DatasetStatus::Available);

        auto datasets = md::DatasetReader<md::ExportMetadata>::datasets(coreTxn, filter);
        for (const auto& dataset : datasets) {
            eventsHolder.addEvent(
                EVENT_EXPORTED,
                dataset.metadata().region(),
                branchId,
                dataset.metadata().basic().created());
        }
    }

    return eventsHolder;
}

} // namespace wiki
} // namespace maps
