#!/bin/sh
# System test seed script — validates backend is ready and loads test data
# Called from docker-compose.test.yml seed container

BASE=http://backend:8080

echo "========================================="
echo " CannaManage System Test Seed"
echo "========================================="

# Wait for backend to be fully ready (Flyway migrations complete)
echo "[1/3] Waiting for backend health..."
RETRIES=0
MAX_RETRIES=30
until curl -sf "$BASE/actuator/health" > /dev/null 2>&1; do
  RETRIES=$((RETRIES + 1))
  if [ $RETRIES -ge $MAX_RETRIES ]; then
    echo "ERROR: Backend not healthy after ${MAX_RETRIES} attempts. Aborting."
    exit 1
  fi
  echo "  ... attempt $RETRIES/$MAX_RETRIES"
  sleep 3
done
echo "  ✓ Backend is healthy"

# Load seed data into PostgreSQL via backend's actuator (if available)
# or directly into the database
echo "[2/3] Loading seed data..."

# Try to load via psql if available in the seed container
# Since we use curlimages/curl, we'll use the backend API to verify data
# The actual SQL seed is loaded via docker-entrypoint-initdb.d mount on the db container

# Verify the API is responding with expected structure
HEALTH=$(curl -sf "$BASE/actuator/health" 2>/dev/null)
if echo "$HEALTH" | grep -q '"status"'; then
  echo "  ✓ Backend API responding correctly"
else
  echo "  ⚠ Backend API response unexpected: $HEALTH"
fi

echo "[3/3] Validating seed data..."
# Try login with seeded admin credentials to verify auth works
LOGIN_RESPONSE=$(curl -sf -X POST "$BASE/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@test.de","password":"test123"}' 2>/dev/null)

if echo "$LOGIN_RESPONSE" | grep -q "accessToken\|token\|access_token"; then
  echo "  ✓ Admin login successful — seed data verified"
elif [ -z "$LOGIN_RESPONSE" ]; then
  echo "  ⚠ Login endpoint not available (backend may not have auth wired yet)"
  echo "  → Continuing anyway — system test will use mock fallback if needed"
else
  echo "  ⚠ Login response: $LOGIN_RESPONSE"
  echo "  → Continuing — the test harness is ready for when auth is wired"
fi

echo ""
echo "========================================="
echo " Seed complete — ready for Playwright"
echo "========================================="
exit 0
