FindOpenSSL: Fix regression in dependency on threads

Since commit 1b7804edd0 (FindOpenSSL: use extra dependencies from
pkg-config as well, 2022-12-05, v3.26.0-rc1~227^2) we conditionally find
Threads but unconditionally depend on it.  Make the conditions
consistent.

Fixes: #24505
diff --git a/Modules/FindOpenSSL.cmake b/Modules/FindOpenSSL.cmake
index f876f43..ae1148d 100644
--- a/Modules/FindOpenSSL.cmake
+++ b/Modules/FindOpenSSL.cmake
@@ -125,6 +125,7 @@
     endif()
     if(_OpenSSL_libs)
       unset(_OpenSSL_has_dependency_dl)
+      unset(_OpenSSL_has_dependency_threads)
       foreach(_OPENSSL_DEP_LIB IN LISTS _OpenSSL_libs)
         if (_OPENSSL_DEP_LIB STREQUAL "ssl" OR _OPENSSL_DEP_LIB STREQUAL "crypto")
           # ignoring: these are the targets
@@ -140,6 +141,7 @@
       unset(_OPENSSL_DEP_LIB)
     else()
       set(_OpenSSL_has_dependency_dl TRUE)
+      set(_OpenSSL_has_dependency_threads TRUE)
       find_package(Threads)
     endif()
     unset(_OpenSSL_libs)
@@ -149,12 +151,12 @@
 endmacro()
 
 function(_OpenSSL_add_dependencies libraries_var)
-  if(CMAKE_THREAD_LIBS_INIT)
-    list(APPEND ${libraries_var} ${CMAKE_THREAD_LIBS_INIT})
-  endif()
   if(_OpenSSL_has_dependency_zlib)
     list(APPEND ${libraries_var} ${ZLIB_LIBRARY})
   endif()
+  if(_OpenSSL_has_dependency_threads)
+    list(APPEND ${libraries_var} ${CMAKE_THREAD_LIBS_INIT})
+  endif()
   if(_OpenSSL_has_dependency_dl)
     list(APPEND ${libraries_var} ${CMAKE_DL_LIBS})
   endif()
@@ -164,12 +166,17 @@
 
 function(_OpenSSL_target_add_dependencies target)
   if(_OpenSSL_has_dependencies)
-    set_property( TARGET ${target} APPEND PROPERTY INTERFACE_LINK_LIBRARIES Threads::Threads ${_OpenSSL_extra_static_deps})
+    if(_OpenSSL_has_dependency_zlib)
+      set_property( TARGET ${target} APPEND PROPERTY INTERFACE_LINK_LIBRARIES ZLIB::ZLIB )
+    endif()
+    if(_OpenSSL_has_dependency_threads)
+      set_property( TARGET ${target} APPEND PROPERTY INTERFACE_LINK_LIBRARIES Threads::Threads)
+    endif()
     if(_OpenSSL_has_dependency_dl)
       set_property( TARGET ${target} APPEND PROPERTY INTERFACE_LINK_LIBRARIES ${CMAKE_DL_LIBS} )
     endif()
-    if(_OpenSSL_has_dependency_zlib)
-      set_property( TARGET ${target} APPEND PROPERTY INTERFACE_LINK_LIBRARIES ZLIB::ZLIB )
+    if(_OpenSSL_extra_static_deps)
+      set_property( TARGET ${target} APPEND PROPERTY INTERFACE_LINK_LIBRARIES ${_OpenSSL_extra_static_deps})
     endif()
   endif()
   if(WIN32 AND OPENSSL_USE_STATIC_LIBS)
@@ -758,4 +765,5 @@
 unset(_OPENSSL_NAME_POSTFIX)
 unset(_OpenSSL_extra_static_deps)
 unset(_OpenSSL_has_dependency_dl)
+unset(_OpenSSL_has_dependency_threads)
 unset(_OpenSSL_has_dependency_zlib)