version: '3.9'

services:
  # ── MySQL Database ───────────────────────────────────
  db:
    image: mysql:8.0
    container_name: portfolio_db
    restart: unless-stopped
    environment:
      MYSQL_DATABASE: ${DB_NAME:-portfolio_db}
      MYSQL_USER: ${DB_USER:-portfolio_user}
      MYSQL_PASSWORD: ${DB_PASSWORD:-securepassword}
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-rootpassword}
    volumes:
      - mysql_data:/var/lib/mysql
      - ./docker/mysql-init.sql:/docker-entrypoint-initdb.d/init.sql:ro
    ports:
      - "3306:3306"
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD:-rootpassword}"]
      interval: 10s
      timeout: 5s
      retries: 5
    networks:
      - portfolio_net

  # ── Django Application ───────────────────────────────
  web:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: portfolio_web
    restart: unless-stopped
    depends_on:
      db:
        condition: service_healthy
    env_file:
      - .env
    environment:
      DB_HOST: db
      DB_PORT: 3306
    volumes:
      - media_vol:/app/media
      - static_vol:/app/static_root
    ports:
      - "8000:8000"
    command: >
      sh -c "python manage.py migrate --noinput &&
             python manage.py collectstatic --noinput &&
             gunicorn devops_portfolio.wsgi:application
             --bind 0.0.0.0:8000
             --workers 3
             --timeout 120
             --access-logfile -
             --error-logfile -"
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/"]
      interval: 30s
      timeout: 10s
      retries: 3
    networks:
      - portfolio_net

  # ── Nginx Reverse Proxy ──────────────────────────────
  nginx:
    image: nginx:alpine
    container_name: portfolio_nginx
    restart: unless-stopped
    depends_on:
      - web
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./docker/nginx.conf:/etc/nginx/conf.d/default.conf:ro
      - media_vol:/app/media:ro
      - static_vol:/app/static_root:ro
      - ./docker/ssl:/etc/nginx/ssl:ro
    networks:
      - portfolio_net

volumes:
  mysql_data:
  media_vol:
  static_vol:

networks:
  portfolio_net:
    driver: bridge
