#!/bin/bash
# Start a MySQL 8 container, wait for it to be ready, run lifecycle integration tests, and clean up.
set -e

CONTAINER_NAME="lc-mysql-$(date +%s)"
PORT=13307

echo "Starting MySQL container: $CONTAINER_NAME on port $PORT"
docker run -d \
  --name "$CONTAINER_NAME" \
  -e MYSQL_ROOT_PASSWORD=secret \
  -e MYSQL_DATABASE=pangolin_test \
  -p "$PORT:3306" \
  mysql:8 >/dev/null

cleanup() {
  echo "Stopping container $CONTAINER_NAME"
  docker stop "$CONTAINER_NAME" >/dev/null 2>&1 || true
  docker rm   "$CONTAINER_NAME" >/dev/null 2>&1 || true
}
trap cleanup EXIT

# Wait for MySQL to be ready (max 60 s)
echo "Waiting for MySQL to be ready..."
for i in $(seq 1 30); do
  if docker exec "$CONTAINER_NAME" mysqladmin ping --silent 2>/dev/null; then
    echo "MySQL ready after ${i}*2 seconds"
    break
  fi
  sleep 2
done

DSN="root:secret@tcp(127.0.0.1:${PORT})/pangolin_test"
echo "Running lifecycle integration tests with DSN=$DSN"

PANGOLIN_TEST_DSN="$DSN" go test -tags integration \
  ./internal/nodes/... \
  -run "TestLifecycle" \
  -v -count=1 -timeout 120s

echo "Tests complete"
