# Find or fetch Google Test
include(FetchContent)
include(GoogleTest)

FetchContent_Declare(
    googletest
    GIT_REPOSITORY https://github.com/google/googletest.git
    GIT_TAG release-1.12.1
)

# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)

# List of active test files
set(TEST_SOURCES
    test_probmodels.cc
    test_psmodels.cc
    test_ptmodels.cc
    test_mavhmodels.cc
    test_mavpsmodels.cc
    test_mavptmodels.cc
    test_mavtrans.cc
    test_netfunc.cc
    test_utils.cc
    test_c_api.cc
    test_runner.cc
)

# Avoid the RUN_TESTS utility target generated by Visual Studio. MSBuild target
# names are case-insensitive, so an executable named run_tests collides with it.
add_executable(spiced_tests ${TEST_SOURCES})

# Include directories
target_include_directories(spiced_tests PRIVATE
    "${CMAKE_SOURCE_DIR}/include"
)

# Find OpenMP for test compilation
find_package(OpenMP REQUIRED)

# test_runner.cc supplies main(), so link gtest without gtest_main.
target_link_libraries(spiced_tests PRIVATE
    spiced
    ann
    gtest
    OpenMP::OpenMP_CXX
)

# Windows has no build-tree RPATH. Put the shared libraries beside the test
# executable so both post-build discovery and the later CTest run can load them.
if(WIN32)
    add_custom_command(TARGET spiced_tests POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
            $<TARGET_FILE:spiced>
            $<TARGET_FILE:ann>
            $<TARGET_FILE_DIR:spiced_tests>
        COMMAND_EXPAND_LISTS
    )
endif()

# Discover and add individual tests to CTest
gtest_discover_tests(
    spiced_tests
    DISCOVERY_TIMEOUT 30
    WORKING_DIRECTORY $<TARGET_FILE_DIR:spiced_tests>
)

# Optional: Set RPATH for finding shared libraries at runtime
if(APPLE)
    set_target_properties(spiced_tests PROPERTIES
        BUILD_RPATH "@loader_path/../lib"
        INSTALL_RPATH "@loader_path/../lib"
    )
elseif(UNIX AND NOT APPLE)
    set_target_properties(spiced_tests PROPERTIES
        BUILD_RPATH "$ORIGIN/../lib"
        INSTALL_RPATH "$ORIGIN/../lib"
    )
endif()
