#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
TMP_DIR="${ROOT_DIR}/tmp"
JNA_TMP_DIR="${TMP_DIR}/jna"
JAVA_TMP_DIR="${TMP_DIR}/java"
PODMAN_LOG="${TMP_DIR}/podman-service.log"
PODMAN_SOCK_PATH="/run/user/$(id -u)/podman/podman.sock"
PODMAN_SOCK="unix://${PODMAN_SOCK_PATH}"
PODMAN_PID=""

if ! command -v podman >/dev/null 2>&1; then
  echo "ERROR: podman 未安装，无法执行严格模式迁移验证。" >&2
  exit 1
fi

mkdir -p "${JNA_TMP_DIR}" "${JAVA_TMP_DIR}"

cleanup() {
  if [[ -n "${PODMAN_PID}" ]] && kill -0 "${PODMAN_PID}" >/dev/null 2>&1; then
    kill "${PODMAN_PID}" >/dev/null 2>&1 || true
    wait "${PODMAN_PID}" >/dev/null 2>&1 || true
  fi
}
trap cleanup EXIT

cd "${ROOT_DIR}"
podman system service --time=0 "${PODMAN_SOCK}" > "${PODMAN_LOG}" 2>&1 &
PODMAN_PID=$!

for _ in {1..30}; do
  if [[ -S "${PODMAN_SOCK_PATH}" ]] && podman --url "${PODMAN_SOCK}" info >/dev/null 2>&1; then
    break
  fi
  sleep 1
done

if ! [[ -S "${PODMAN_SOCK_PATH}" ]] || ! podman --url "${PODMAN_SOCK}" info >/dev/null 2>&1; then
  echo "ERROR: podman service 未就绪，无法执行严格模式迁移验证。" >&2
  if [[ -f "${PODMAN_LOG}" ]]; then
    echo "----- podman service log (tail) -----" >&2
    tail -n 80 "${PODMAN_LOG}" >&2 || true
  fi
  exit 1
fi

export DOCKER_HOST="${PODMAN_SOCK}"
export TESTCONTAINERS_RYUK_DISABLED="true"

mvn -B -DskipTests=false -Dmigration.test.strict=true \
  -Djna.tmpdir="${JNA_TMP_DIR}" \
  -Djava.io.tmpdir="${JAVA_TMP_DIR}" \
  clean verify

# 显式执行关键集成测试（之前被默认排除）
echo "=== 执行关键集成测试集合 ==="
mvn -B test -Dtest=UserOperationJourneyTest,CacheConfigIntegrationTest,SchemaVerificationTest \
  -DfailIfNoTests=false \
  -Djourney.test.enabled=true \
  -Djna.tmpdir="${JNA_TMP_DIR}" \
  -Djava.io.tmpdir="${JAVA_TMP_DIR}"
