#include "yt_delivery.h"

#include <util/generic/yexception.h>

namespace NSaasLB {
    void TYtDeliveryStorage::InitDeliveries(const TVector<TString>& deliveries) {
        AvailableDeliveries = {deliveries.begin(), deliveries.end()};
    }

    std::optional<NLogBroker::SingleModifyRequest> TYtDeliveryStorage::Add(const TString& topicPath, const TString& delivery) {
        CheckDeliveryName(delivery);
        if (Deliveries[topicPath].count(delivery)) {
            return {};
        }
        Deliveries[topicPath].insert(delivery);
        NLogBroker::SingleModifyRequest request;
        auto req = request.mutable_add_topic_to_yt_delivery();
        req->set_topic(topicPath);
        req->set_delivery(delivery);
        return request;
    }

    std::optional<NLogBroker::SingleModifyRequest> TYtDeliveryStorage::Remove(const TString& topicPath, const TString& delivery) {
        CheckDeliveryName(delivery);
        if (!Deliveries.count(topicPath) || !Deliveries[topicPath].count(delivery)) {
            return {};
        }
        Deliveries[topicPath].erase(delivery);
        if (Deliveries[topicPath].empty()) {
            Deliveries.erase(topicPath);
        }
        NLogBroker::SingleModifyRequest request;
        auto req = request.mutable_remove_topic_from_yt_delivery();
        req->set_topic(topicPath);
        req->set_delivery(delivery);
        return request;
    }

    TVector<TString> TYtDeliveryStorage::GetFor(const TString& topicPath) const {
        auto it = Deliveries.find(topicPath);
        if (it == Deliveries.end()) {
            return {};
        }
        return {it->second.begin(), it->second.end()};
    }

    void TYtDeliveryStorage::Load(const TString& topicPath, const NLogBroker::DescribeTopicResult& topicDescription) {
        for (auto& delivery : topicDescription.yt_deliveries()) {
            Add(topicPath, delivery);
        }
    }

    void TYtDeliveryStorage::CheckDeliveryName(const TString& delivery) const {
        if (!AvailableDeliveries.count(delivery)) {
            ythrow yexception() << "yt delivery '" << delivery << "' not exist";
        }
    }
}
