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
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:5000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s
    command: >
      sh -c "
        echo '⏳ Waiting for MySQL to be ready for connections...'
        for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
          if mysql -h db -u vendinguser -pvendingpass -e 'SELECT 1' >/dev/null 2>&1; then
            echo '✓ MySQL is ready!'
            break
          fi
          echo 'Waiting for MySQL... (attempt' $$i'/15)'
          sleep 3
        done
        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
      "

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

networks:
  vending-network:
    driver: bridge

volumes:
  mysql_data:
    driver: local