"""
Simple script / pytest test to verify MongoDB connection.

Usage as script (recommended for quick check):

    cd backend
    # Ensure MONGODB_URI is set in environment or .env
    python -m tests.test_mongodb_connection

It will:
  - Read MONGODB_URI from environment (preferred)
  - If missing, fallback to a hardcoded URI for local testing
  - Try to run admin.command(\"ping\") against MongoDB
"""

from __future__ import annotations

import asyncio
import os

import pytest
from motor.motor_asyncio import AsyncIOMotorClient


# Fallback URI for local testing ONLY.
# Prefer setting MONGODB_URI in backend/.env or your shell instead of relying on this.
HARDCODED_TEST_URI = (
    "mongodb+srv://20010841:vuhoanganh1704@cluster0.h6qro.mongodb.net/"
    "?appName=Cluster0"
)


async def _ping_mongodb(uri: str) -> None:
    print(f"🔌 Testing MongoDB connection with URI: {uri!r}")
    client = AsyncIOMotorClient(uri, serverSelectionTimeoutMS=5000)
    try:
        await client.admin.command("ping")
        print("✅ MongoDB ping succeeded")
    finally:
        client.close()


@pytest.mark.asyncio
async def test_mongodb_connection() -> None:
    """Pytest-compatible test to verify MongoDB connection."""
    uri = os.getenv("MONGODB_URI") or HARDCODED_TEST_URI
    await _ping_mongodb(uri)


if __name__ == "__main__":
    # Allow running as a standalone script: python -m tests.test_mongodb_connection
    uri = os.getenv("MONGODB_URI") or HARDCODED_TEST_URI
    asyncio.run(_ping_mongodb(uri))


