#!/bin/bash
# Checks that the configured MongoDB server is reachable and prints a ready-to-use
# connection string. Reads the same environment variables the application uses.
set -euo pipefail

HOST="${MONGODB_HOST:-localhost}"
PORT="${MONGODB_PORT:-27017}"
DATABASE="${MONGODB_DATABASE:-parser_db}"
USERNAME="${MONGODB_USERNAME:-}"
AUTH_DB="${MONGODB_AUTH_DATABASE:-admin}"

echo "🔍 Checking MongoDB connectivity..."
echo "======================================"
echo "📡 Probing ${HOST}:${PORT}..."

if nc -z "$HOST" "$PORT"; then
    echo "✅ MongoDB server is reachable"
else
    echo "❌ MongoDB server is unreachable"
    echo "   Check that the server is running and that MONGODB_HOST/MONGODB_PORT are correct."
    exit 1
fi

echo ""
echo "🔐 Configured connection:"
echo "  Host:     ${HOST}:${PORT}"
echo "  Database: ${DATABASE}"
echo "  Username: ${USERNAME:-<MONGODB_USERNAME not set>}"
echo "  Auth DB:  ${AUTH_DB}"

echo ""
echo "📝 Verify credentials with:"
echo "  mongosh \"mongodb://${USERNAME:-<user>}@${HOST}:${PORT}/${DATABASE}?authSource=${AUTH_DB}\""
echo "  (mongosh will prompt for the password; never pass it on the command line)"

echo ""
echo "⚠️  If authentication fails, check:"
echo "  1. MONGODB_USERNAME / MONGODB_PASSWORD are exported"
echo "  2. Firewall rules on the MongoDB host"
echo "  3. The user's grants on '${DATABASE}'"
echo "  4. That authSource matches how the user was created"
