#include "propagate_defaults.h"

#include <saas/deploy_manager/protos/sla_description.pb.h>
#include <saas/deploy_manager/server/client/client.h>
#include <saas/deploy_manager/scripts/common/sla_processing/sla_processing.h>

#include <util/string/type.h>

namespace {
    void ReportError(IDeployInfoRequest& request, const TString& message, ui16 code = 400) {
        request.Output() << "HTTP/1.1 " << code << " \r\n\r\n";
        request.Output() << message;
    }
}

namespace NRTYDeploy {


    bool TScriptPropagateDefault::Process(IDeployInfoRequest& request) {
        const TCgiParameters& params = request.GetRD().CgiParam;

        const TString& service = params.Get("service");
        const TString& ctype = params.Get("ctype");
        const bool isDryRun = params.Has("dry_run") && IsTrue(params.Get("dry_run"));

        if (service.empty()) {
            ReportError(request, "service is missing");
            return false;
        }
        if (ctype.empty()) {
            ReportError(request, "ctype is missing");
            return false;
        }

        NSaasProto::TSlaDescription description;
        if (!TryGetSLADescription(service, request.GetStorage(), description)) {
            ReportError(request, "Failed to load sla description");
            return false;
        }

        for (const auto& it: StringSplitter(ctype).Split(',').SkipEmpty()) {
            const TString ctypeStr(it.Token());
            NSaasProto::TSlaDescription descriptionDef;
            if (!TryGetSLADefault(ctypeStr, request.GetStorage(), descriptionDef)) {
                ReportError(request, "Failed to load sla description default for ctype " + ctypeStr);
                return false;
            }


            MergeSLA(descriptionDef, description);
        }

        if (!isDryRun) {
            StoreSLADescription(service, request.GetStorage(), description);
        }

        request.Output() << "HTTP/1.1 200 \r\n\r\n" << description.DebugString() << "\n";

        return true;
    }

    IScript::TFactory::TRegistrator<TScriptPropagateDefault> TScriptPropagateDefault::Registrator("propagate_sla_default");
}

