include(GoogleTest)

add_executable(
    fesa_unit_tests
    unit/build_info_test.cpp
    unit/core/diagnostic_test.cpp
    unit/core/source_identity_test.cpp
    unit/core/status_test.cpp
    unit/math/matrix_test.cpp
    unit/math/vector_test.cpp
    unit/io/abaqus/input_reader_test.cpp
    unit/io/abaqus/input_syntax_test.cpp
    unit/model/domain_test.cpp
    unit/model/model_types_test.cpp
)

target_link_libraries(
    fesa_unit_tests
    PRIVATE
        fesa_solver
        GTest::gtest_main
)

if(WIN32)
    if(NOT TARGET MKL::mkl_intel_thread OR NOT TARGET MKL::mkl_core OR
       NOT OMP_DLL_DIR OR NOT OMP_DLLNAME)
        message(FATAL_ERROR "The oneMKL runtime files required by tests were not resolved")
    endif()

    file(GLOB _fesa_mkl_dispatch_dlls "${MKL_ROOT}/bin/mkl_def.*.dll")
    if(NOT _fesa_mkl_dispatch_dlls)
        message(FATAL_ERROR "The oneMKL default dispatch runtime was not resolved")
    endif()
    list(SORT _fesa_mkl_dispatch_dlls COMPARE NATURAL ORDER DESCENDING)
    list(GET _fesa_mkl_dispatch_dlls 0 _fesa_mkl_dispatch_dll)

    # Stage dynamic backend dependencies before post-build GoogleTest
    # discovery; the exact validation commands do not assume oneAPI in PATH.
    add_custom_command(
        TARGET fesa_unit_tests
        POST_BUILD
        COMMAND "${CMAKE_COMMAND}" -E copy_if_different
                "$<TARGET_FILE:MKL::mkl_intel_thread>"
                "$<TARGET_FILE_DIR:fesa_unit_tests>"
        COMMAND "${CMAKE_COMMAND}" -E copy_if_different
                "$<TARGET_FILE:MKL::mkl_core>"
                "$<TARGET_FILE_DIR:fesa_unit_tests>"
        COMMAND "${CMAKE_COMMAND}" -E copy_if_different
                "${OMP_DLL_DIR}/${OMP_DLLNAME}"
                "$<TARGET_FILE_DIR:fesa_unit_tests>"
        COMMAND "${CMAKE_COMMAND}" -E copy_if_different
                "${_fesa_mkl_dispatch_dll}"
                "$<TARGET_FILE_DIR:fesa_unit_tests>"
    )

    unset(_fesa_mkl_dispatch_dll)
    unset(_fesa_mkl_dispatch_dlls)
endif()

gtest_discover_tests(
    fesa_unit_tests
    PROPERTIES
        LABELS "linear-static-3d-euler-beam;unit"
)

add_custom_target(fesa_tests DEPENDS fesa_unit_tests)
