version: '3.8'

services:
  # Database service for RPS
  client-db:
    image: mysql:8.0
    container_name: client-mysql-database
    environment:
      - MYSQL_DATABASE=${MYSQL_DATABASE}
      - MYSQL_USER=${MYSQL_USER}
      - MYSQL_PASSWORD=${MYSQL_PASSWORD}
      - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
    volumes:
      - client_mysql_data:/var/lib/mysql
    networks:
      - client-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
  client-backend:
    build: ./backend
    container_name: client-backend-image
    env_file:
      - .env
    command: >
      sh -c "
      echo 'Waiting for MySQL...' &&
      until nc -z client-db 3306; do sleep 2; done &&
      echo 'MySQL is ready. Starting Django...' &&
      python manage.py migrate --noinput &&
      python manage.py collectstatic --noinput &&
      gunicorn --bind 0.0.0.0:8794 --workers 4 --timeout 90 --access-logfile /var/log/gunicorn-access.log --error-logfile /var/log/gunicorn-error.log RPS_project.wsgi:application
      "
    depends_on:
      - client-db
    environment:
      - DB_HOST=client-db
      - DB_NAME=${MYSQL_DATABASE}
      - DB_USER=${MYSQL_USER}
      - DB_PASSWORD=${MYSQL_PASSWORD}
    volumes:
      - client_static_data:/usr/src/app/RPS_project/staticfiles
      - client_media_data:/usr/src/app/RPS_project/media
      - ./logs:/var/log
    networks:
      - client-network
    restart: on-failure

  # React build
  client-frontend-build:
    build:
      context: ./client-side
      target: builder
    container_name: client-react-image
    volumes:
      - client_react_build:/app/dist
    networks:
      - client-network

  # Nginx proxy
  client-nginx:
    image: nginx:alpine
    container_name: client-nginx
    ports:
      - "8794:80"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
      - client_static_data:/staticfiles:ro
      - client_media_data:/mediafiles:ro
      - client_react_build:/var/www/html:ro
    depends_on:
      - client-backend
      - client-frontend-build
    networks:
      - client-network
    restart: unless-stopped

# 🧱 Global volume declarations (MUST be at root level)
volumes:
  client_mysql_data:
  client_static_data:
  client_media_data:
  client_react_build:

networks:
  client-network:
    driver: bridge
