version: '3.8'
services:
  # Database service for RPS
  rps-db:
    image: mysql:8.0
    container_name: rps-mysql-database
    environment:
      - MYSQL_DATABASE=${MYSQL_DATABASE}
      - MYSQL_USER=${MYSQL_USER}
      - MYSQL_PASSWORD=${MYSQL_PASSWORD}
      - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
    volumes:
      - rps_mysql_data:/var/lib/mysql
    networks:
      - rps-network
    
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD}"]
      interval: 10s
      timeout: 10s
      retries: 10
      start_period: 30s
  
  # Django backend for RPS
  rps-backend:
    build: ./backend
    container_name: rps-backend-image
    env_file:
      - .env
    command: >
      sh -c "
      python manage.py makemigrations &&
      python manage.py migrate &&
      python manage.py collectstatic --noinput &&
      gunicorn --bind 0.0.0.0:8789 --workers 4 --timeout 90 --access-logfile /var/log/gunicorn-access.log --error-logfile /var/log/gunicorn-error.log RPS_project.wsgi:application
      "
    depends_on:
      - rps-db
      
    environment:
      - DB_HOST=rps-db  # Updated to match service name
      - DB_NAME=${MYSQL_DATABASE}
      - DB_USER=${MYSQL_USER}
      - DB_PASSWORD=${MYSQL_PASSWORD}
    volumes:
      - rps_static_data:/usr/src/app/RPS_project/staticfiles
      - rps_media_data:/usr/src/app/RPS_project/media
      - ./logs:/var/log
    networks:
      - rps-network
    restart: on-failure
  
  # React build stage for RPS
  rps-frontend-build:
    build:
      context: ./frontend
      target: builder
    container_name: rps-react-image
    volumes:
      - rps_react_build:/app/build
    networks:
      - rps-network
  
  # Nginx proxy server for RPS
  rps-nginx:
    image: nginx:alpine
    container_name: rps-nginx
    ports:
      - "8789:80"  # Different port from jitbot (8786)
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
      - rps_static_data:/staticfiles:ro
      - rps_media_data:/mediafiles:ro
      - rps_react_build:/var/www/html:ro
    depends_on:
      - rps-backend
      - rps-frontend-build
    networks:
      - rps-network
    restart: unless-stopped

volumes:
  rps_mysql_data:
  rps_static_data:
  rps_media_data:
  rps_react_build:

networks:
  rps-network:
    driver: bridge