#!/bin/bash
# Creates the personal_test database and writes .env.test
# Run once before integration tests: npm run test:setup

set -e

PG_CONTAINER=postgres-personal
PG_USER=personal
PG_PASS=personalpassword123
TEST_DB=personal_test

# Discover the container's bridge IP (accessible from the host on Linux)
PG_HOST=$(docker inspect "$PG_CONTAINER" \
  --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' 2>/dev/null | head -1)

if [ -z "$PG_HOST" ]; then
  echo "ERROR: Could not find container '$PG_CONTAINER'"
  exit 1
fi

echo "Postgres container at $PG_HOST:5432"

# Create test database (ignore error if it already exists)
docker exec "$PG_CONTAINER" psql -U "$PG_USER" -d postgres \
  -c "CREATE DATABASE $TEST_DB;" 2>/dev/null || true

# Wipe and rebuild schema from production (schema only, no data)
echo "Copying schema from $PG_USER to $TEST_DB..."
docker exec "$PG_CONTAINER" pg_dump -U "$PG_USER" --schema-only "$PG_USER" \
  | docker exec -i "$PG_CONTAINER" psql -U "$PG_USER" -d "$TEST_DB" -q

echo "Schema ready."

# Write .env.test
cat > "$(dirname "$0")/../.env.test" << EOF
DATABASE_URL=postgresql://$PG_USER:$PG_PASS@$PG_HOST:5432/$TEST_DB
EOF

echo ".env.test written — integration tests can now run with: npm run test:integration"
