services:
  mongo:
    image: mongo:7.0
    command: --replSet rs0 --bind_ip_all  # Removed --quiet for better visibility
    restart: unless-stopped
    ports:
      - 27017:27017
    volumes:
      - mongo_storage:/data/db
    healthcheck:
      test: echo 'db.runCommand("ping").ok' | mongosh --quiet
      interval: 5s
      timeout: 30s
      retries: 5

  mongo-rs-init:
    image: mongo:7.0
    depends_on:
      mongo:
        condition: service_healthy
    restart: on-failure
    entrypoint:
      - bash
      - -c
      - |
        # Retry loop to wait for MongoDB readiness
        until mongosh --host mongo --eval "try { rs.status().ok } catch { quit(1) }"; do
          echo "Waiting for MongoDB to be ready..."
          sleep 2
        done
        
        # Initiate replica set if needed
        mongosh --host mongo --eval '
          if (!rs.status().ok) {
            rs.initiate({
              _id: "rs0",
              version: 1,
              members: [{ _id: 0, host: "mongo:27017" }]
            })
          }
        '
        echo "Replica set initialization complete"

volumes:
  mongo_storage: