#include "st_agent.h"

#include "st_tag.h"
#include <maps/libs/chrono/include/time_point.h>
#include <yandex/maps/wiki/common/secrets.h>

namespace maps::wiki::user_edits_metrics {

static const std::string ST_BASE_URL = "https://st-api.yandex-team.ru";

StAgent::StAgent(
    std::string queueKey,
    const std::string& token)
        : stGateway_(st::Configuration(ST_BASE_URL, token))
        , queueKey_(std::move(queueKey))
{}

st::Issue StAgent::createIssue(
    const std::string& summary,
    const std::string& description,
    const std::unordered_set<std::string>& followers) const
{
    st::IssuePatch issuePatch;
    issuePatch.summary().set(summary);
    issuePatch.description().set(description);
    issuePatch.followers().set(followers);
    return stGateway_.createIssue(queueKey_, issuePatch);
}

std::optional<st::Issue> StAgent::findOpenedIssue(const std::string& summary) const
{
    const auto query = "Queue: " + queueKey_ + " and Status: Open and Summary: \"" + summary
        + "\" \"Sort By\": Created DESC";
    auto issues = stGateway_.loadIssues(query);

    if (issues.begin() != issues.end()) {
        return *issues.begin();
    } else {
        return {};
    }
}

void StAgent::updateIssue(
    const st::Issue& issue,
    const std::string& comment,
    std::optional<chrono::TimePoint> newTagTime) const
{
    stGateway_.createComment(issue.key(), comment);
    if (newTagTime) {
        st::IssuePatch issuePatch;
        for (const auto& tag: issue.tags()) {
            // Delete old tags with date, because we use tag with date for saving last update time
            if (tagFormatCorrect(tag)) {
                issuePatch.tags().subtract(tag);
            }
        }
        issuePatch.tags().append(timeToTag(newTagTime.value()));
        stGateway_.patchIssue(issue.key(), issuePatch);
    }
}

std::string StAgent::getToken()
{
    return common::secrets::tokenByKey(common::secrets::Key::RobotWikimapStToken);
}

} // namespace maps::wiki::user_edits_metrics
