version: '3.8'

services:
  # MongoDB Database
  mongodb:
    image: mongo:7.0
    container_name: business_platform_mongodb
    restart: always
    ports:
      - "127.0.0.1:27017:27017"  # Only accessible from localhost
    environment:
      MONGO_INITDB_DATABASE: business_platform_db
      MONGO_INITDB_ROOT_USERNAME: ${MONGO_USER}
      MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASSWORD}
    volumes:
      - mongodb_data:/data/db
      - mongodb_config:/data/configdb
    networks:
      - business_network
    healthcheck:
      test: echo 'db.runCommand("ping").ok' | mongosh localhost:27017/test --quiet
      interval: 10s
      timeout: 5s
      retries: 5

  # Django Application with Gunicorn
  django:
    build:
      context: .
      dockerfile: Dockerfile.prod
    container_name: business_platform_django
    restart: always
    volumes:
      - static_volume:/app/staticfiles
      - media_volume:/app/media
      - ./db.sqlite3:/app/db.sqlite3 
    expose:
      - "8000"
    env_file:
      - .env.prod
    environment:
      - DEBUG=False
      - MONGO_HOST=mongodb
      - MONGO_PORT=27017
    depends_on:
      mongodb:
        condition: service_healthy
    networks:
      - business_network

  # Nginx Reverse Proxy
  nginx:
    image: nginx:alpine
    container_name: business_platform_nginx
    restart: always
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./nginx/conf.d:/etc/nginx/conf.d:ro
      - static_volume:/app/staticfiles:ro
      - media_volume:/app/media:ro
      - ./certbot/conf:/etc/letsencrypt:ro
      - ./certbot/www:/var/www/certbot:ro
    depends_on:
      - django
    networks:
      - business_network

  # Certbot for SSL certificates
  certbot:
    image: certbot/certbot
    container_name: business_platform_certbot
    volumes:
      - ./certbot/conf:/etc/letsencrypt
      - ./certbot/www:/var/www/certbot
    entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'"

volumes:
  mongodb_data:
    driver: local
  mongodb_config:
    driver: local
  static_volume:
  media_volume:

networks:
  business_network:
    driver: bridge
