#!/usr/bin/env bash
#
# Regenerates customer-connect-api-spec.yaml from the live springdoc /v3/api-docs output.
# Runs OpenApiSpecTest.writeApiSpecYaml (gated by -Dgenerate.api.spec=true) which writes the
# yaml to the project root; this script then moves it to docusaurus/static/.
#
# Usage: ./docs.sh [--skip-tests] [-- <extra maven args>]
#   --skip-tests   skip the full test suite pass (step 1); only re-run the spec writer.
#                  Faster, but relies on restdocs/javadoc-json artifacts already present
#                  in target/ from a previous run.

set -e          # raise exception if error
set -u          # raise exception if unset
set -o pipefail # raise exceptions in pipes

BASENAME=$(basename "$0")
WORKDIR=$(cd "$(dirname "$0")"; pwd -P)
cd "$WORKDIR"

SKIP_TESTS=false
MVN_ARGS=()
for arg in "$@"; do
    case "$arg" in
        --skip-tests) SKIP_TESTS=true ;;
        *) MVN_ARGS+=("$arg") ;;
    esac
done

# --- check java version ---
expected_version=21
if [[ -n ${JAVA_HOME-} ]] && [[ -x "$JAVA_HOME/bin/java" ]]; then
    _java="$JAVA_HOME/bin/java"
elif [[ -n $(type -p java) ]]; then
    _java=java
else
    echo "Missing Java!  Set JAVA_HOME environment variable to the path to a JDK."
    exit 1
fi

version=$("$_java" -version 2>&1 | awk -F '"' '/version/ {print $2}')
if [[ "$version" < $expected_version ]]; then
    echo "This project requires Java $expected_version, but the current JDK version is $version"
    echo "Set JAVA_HOME to the directory of a $expected_version JDK."
    exit 1
fi

[[ ${#MVN_ARGS[@]} -gt 0 ]] && {
    echo "WARN: Passing Maven options: ${MVN_ARGS[*]}" >&2
}

SPEC_SRC="$WORKDIR/customer-connect-api-spec.yaml"
SPEC_DST="$WORKDIR/docusaurus/static/customer-connect-api-spec.yaml"

time \
(
    # 1. Run the full test suite. Restdocs snippets and javadoc-json, which feed the spec,
    #    are written to target/ during this pass. Skipped when --skip-tests is passed.
    if [[ "$SKIP_TESTS" == "true" ]]; then
        echo "Skipping full test suite (step 1) — relying on artifacts already in target/."
    else
        ./mvnw clean test ${MVN_ARGS[@]+"${MVN_ARGS[@]}"}
    fi &&

    # 2. Re-invoke just the spec-writer test with the flag set, so it regenerates
    #    customer-connect-api-spec.yaml from /v3/api-docs using the artifacts above.
    ./mvnw test \
        -Dtest='OpenApiSpecTest#writeApiSpecYaml' \
        -Dgenerate.api.spec=true \
        ${MVN_ARGS[@]+"${MVN_ARGS[@]}"}
)

# 3. Move the generated spec into docusaurus/static/ where the docusaurus site consumes it.
mv "$SPEC_SRC" "$SPEC_DST"

echo
echo "Updated: $SPEC_DST"
