version: "3.9"

services:
  db:
    image: mysql:8.0
    container_name: vending-db
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: rootpass
      MYSQL_DATABASE: vending
      MYSQL_USER: vendinguser
      MYSQL_PASSWORD: vendingpass
    ports:
      - "3307:3306"
    volumes:
      - mysql_data:/var/lib/mysql
    networks:
      - vending-network
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-prootpass"]
      interval: 10s
      timeout: 5s
      retries: 10
      start_period: 30s

  backend:
    build:
      context: ./Machine-Backend
      dockerfile: Dockerfile
    container_name: vending-backend
    env_file:
      - ./Machine-Backend/.env
    ports:
      - "8087:5000"
    volumes:
      - ./Machine-Backend:/app
    networks:
      - vending-network
    depends_on:
      db:
        condition: service_healthy
    restart: always
    command: >
      sh -c "
        python wait_for_db.py &&
        echo '🌱 Running database seed script...' &&
        python seed_user.py &&
        echo '🚀 Starting Gunicorn server...' &&
        gunicorn --bind 0.0.0.0:5000 --workers 2 --timeout 120 run:app
      "
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:5000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

  microservice:
    build:
      context: ./Project
      dockerfile: Dockerfile
    container_name: vending-microservice
    ports:
      - "8088:5001"
    volumes:
      - ./Project:/app
    networks:
      - vending-network
    environment:
      - MAIN_BACKEND_URL=https://iotbackend.rootxwire.com
      - FLASK_ENV=production
      - PYTHONPATH=/app
    restart: always
    healthcheck:
      test: ["CMD", "python", "-c", "import requests; requests.get('http://localhost:5001/', timeout=5)"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 10s

  frontend:
    build:
      context: ./fuse-starter-v20.0.0
      dockerfile: Dockerfile
    container_name: vending-frontend
    ports:
      - "8086:80"
    networks:
      - vending-network
    depends_on:
      - backend
      - microservice
    restart: always

networks:
  vending-network:
    driver: bridge

volumes:
  mysql_data:
    driver: local