#include "ssl_client_ctx_storage.h"

namespace NSrvKernel {


TAtomicSharedPtr<const TSslClientContext> GetSslClientContext(const TString& ciphers, int32_t verifyDepth, const TString& caFile) {
    static THashMap<TString, TAtomicSharedPtr<const TSslClientContext>> contexts;
    static TMutex guard;
    TString key = ciphers + (verifyDepth >= 0 ? ToString(verifyDepth) : TString()) + caFile;
    with_lock (guard) {
        if (auto iter = contexts.find(key); iter != contexts.end()) {
            return iter->second;
        } else {
            // nullptr for server side TLS 1.3 priority
            TSslClientContext ctx(CreateSslClientCtx(ciphers.data(), nullptr));
            if (verifyDepth >= 0) {
                TryRethrowError(ctx.SetVerifyDepth(verifyDepth));
                TryRethrowError(ctx.SetVerifyPeer());
            }
            bool loaded = true;
            // Since THttpsSetting is being created only in config parsing, it's not required
            // to propagate TError from this point.
            TryRethrowError(ctx.LoadVerifyLocations(caFile.data()).AssignTo(loaded));
            if (!loaded) {
                ythrow yexception() << SslErrorText(GetLastSslError());
            }

            auto res = contexts.insert({key, MakeAtomicShared<const TSslClientContext>(std::move(ctx))});
            Y_VERIFY(res.second);
            return res.first->second;
        }
    }
}

}