#!/bin/bash
# Integration test runner
# Runs only integration suites under test/:
#   - *.integration-spec.ts
#   - *.worker-int-spec.ts
# Requires real MySQL, Redis and BullMQ worker dependencies.
set -e

echo "=== Integration tests ==="

DB_URL="${DATABASE_URL:-mysql://zhixi_user:test@127.0.0.1:3306/zhixi_test}"
REDIS_H="${REDIS_HOST:-127.0.0.1}"
REDIS_P="${REDIS_PORT:-6379}"
REDIS_PW="${REDIS_PASSWORD:-}"

echo "[1/4] Checking MySQL..."
if command -v mysqladmin >/dev/null 2>&1; then
  mysqladmin ping --host="${MYSQL_HOST:-127.0.0.1}" --port="${MYSQL_PORT:-3306}" --user="${MYSQL_USER:-root}" --password="${MYSQL_PASSWORD:-${MYSQL_ROOT_PASSWORD:-root}}" --silent >/dev/null
else
  docker exec mysql mysqladmin ping -u root -p"${MYSQL_ROOT_PASSWORD:-root}" --silent >/dev/null 2>&1 || {
    echo "MySQL not reachable; ensure MySQL is running"
    exit 1
  }
fi

echo "[2/4] Checking Redis..."
if command -v redis-cli >/dev/null 2>&1; then
  if [ -n "$REDIS_PW" ]; then
    redis-cli -h "$REDIS_H" -p "$REDIS_P" -a "$REDIS_PW" ping | grep -q PONG
  else
    redis-cli -h "$REDIS_H" -p "$REDIS_P" ping | grep -q PONG
  fi
else
  echo "redis-cli not found; skipping explicit Redis ping, but integration tests still require Redis"
fi

echo "[3/4] Running Prisma migration..."
npx prisma migrate deploy

echo "[4/4] Running integration suites..."
npm run build --if-present
npx jest --config test/jest-integration.json --runInBand --verbose
