services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: medoracle-app
    image: medoracle-app:latest

    depends_on:
      migrate:
        condition: service_completed_successfully
    environment:
      ENVIRONMENT: ${ENVIRONMENT:-prod}
      DEBUG: ${DEBUG:-false}
      HMR: ${HMR:-0}
      DB_DRIVER: ${DB_DRIVER:-mysql}
      DB_HOST: ${DB_HOST:-db}
      DB_PORT: ${DB_PORT:-3306}
      DB_NAME: ${DB_NAME}
      DB_USER: ${DB_USER}
      DB_PASSWORD: ${DB_PASSWORD}
    volumes:
      - ${UPLOADS_SOURCE:-uploads}:/var/www/html/public/uploads
      # cache and logs are inside the image, no need for volumes in production
      - extensions:/var/www/html/extra/extensions
      - artifacts:/var/www/html/extra/artifacts
    # ports:
      # - "${APP_HTTP_PORT:-8088}:80"  # Internal only, served through nginx
    healthcheck:
      test: ["CMD-SHELL", "curl -f http://localhost/health.php || exit 1"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 30s


  migrate:
    image: medoracle-app:latest
    container_name: medoracle-migrate
    working_dir: /var/www/html
    depends_on:
      db:
        condition: service_healthy
    entrypoint:
      - sh
      - -c
      - |
        set -e
        echo 'Aguardando banco de dados estar completamente pronto...'
        sleep 10

        echo 'Criando arquivo .env se não existir...'
        if [ ! -f .env ]; then
          cp .env.example .env
          sed -i "s/^ENVIRONMENT=.*/ENVIRONMENT=$${ENVIRONMENT}/" .env
          sed -i "s/^DEBUG=.*/DEBUG=$${DEBUG}/" .env
          sed -i "s/^HMR=.*/HMR=$${HMR}/" .env
          sed -i "s/^DB_DRIVER=.*/DB_DRIVER=$${DB_DRIVER}/" .env
          sed -i "s/^DB_HOST=.*/DB_HOST=$${DB_HOST}/" .env
          sed -i "s/^DB_PORT=.*/DB_PORT=$${DB_PORT}/" .env
          sed -i "s/^DB_NAME=.*/DB_NAME=$${DB_NAME}/" .env
          sed -i "s/^DB_USER=.*/DB_USER=$${DB_USER}/" .env
          sed -i "s/^DB_PASSWORD=.*/DB_PASSWORD=$${DB_PASSWORD}/" .env
        fi

        echo 'Testando conexão com o banco...'
        echo "Usando credenciais do ambiente (.env)"
        max_attempts=30
        attempt=0
        until php -r '$$h=getenv("DB_HOST");$$P=getenv("DB_PORT")?:3306;$$u=getenv("DB_USER");$$p=getenv("DB_PASSWORD");$$n=getenv("DB_NAME");try{$$pdo=new PDO("mysql:host=$$h;port=$$P;dbname=$$n",$$u,$$p);echo "OK\n";exit(0);}catch(Throwable $$e){echo "Erro: ".$$e->getMessage()."\n";exit(1);}'; do
          attempt=$$((attempt + 1))
          if [ $$attempt -ge $$max_attempts ]; then
            echo "Falha ao conectar ao banco após $$max_attempts tentativas"
            exit 1
          fi
          echo "Aguardando conexão com o banco... (tentativa $$attempt/$$max_attempts)"
          sleep 2
        done

        echo 'Banco conectado! Executando migrations...'
        php /var/www/html/bin/console migrations:migrate --no-interaction --all-or-nothing=0
        echo 'Migrations executadas com sucesso!'
    environment:
      ENVIRONMENT: ${ENVIRONMENT}
      DEBUG: ${DEBUG}
      HMR: ${HMR}
      DB_DRIVER: ${DB_DRIVER}
      DB_HOST: ${DB_HOST}
      DB_PORT: ${DB_PORT}
      DB_NAME: ${DB_NAME}
      DB_USER: ${DB_USER}
      DB_PASSWORD: ${DB_PASSWORD}
    restart: "no"

  nginx:
    image: nginx:alpine
    container_name: medoracle-nginx
    ports:
      - "${APP_HTTP_PORT:-8088}:80"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
    depends_on:
      app:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost/health"]
      interval: 10s
      timeout: 5s
      retries: 3
      start_period: 10s
    restart: unless-stopped

  db:
    image: mysql:8.0
    container_name: medoracle-db
    environment:
      MYSQL_DATABASE: ${DB_NAME}
      MYSQL_USER: ${DB_USER}
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
    # ports:
      # - "3306:3306"  # Commented out to avoid conflicts in production
      # For local development, use: docker compose --profile dev up
    command: ["--default-authentication-plugin=mysql_native_password", "--character-set-server=utf8mb4", "--collation-server=utf8mb4_unicode_ci"]
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-uroot", "-p${DB_ROOT_PASSWORD}"]
      interval: 10s
      timeout: 5s
      retries: 20
      start_period: 30s
    volumes:
      - dbdata:/var/lib/mysql
    restart: unless-stopped

  # PHPMyAdmin for database management (staging/production)
  # SECURITY: Requires manual login - no auto-authentication
  phpmyadmin:
    image: phpmyadmin:latest
    container_name: medoracle-phpmyadmin
    environment:
      PMA_HOST: db
      PMA_PORT: 3306
      # REMOVED: PMA_USER and PMA_PASSWORD for security
      # Users must login manually with database credentials
      PMA_ARBITRARY: 0
      UPLOAD_LIMIT: 100M
    ports:
      - "${PHPMYADMIN_PORT:-8081}:80"
    depends_on:
      db:
        condition: service_healthy
    restart: unless-stopped

  # Optional dev-only Vite service for HMR
  frontend:
    image: node:22-alpine
    working_dir: /app
    command: sh -lc "npm ci || npm install && npm run dev"
    volumes:
      - .:/app
    ports:
      - "5173:5173"
    profiles: ["dev"]

  # Optional dev-only Mailhog for SMTP testing
  mailhog:
    image: mailhog/mailhog:latest
    ports:
      - "8025:8025"  # UI
      - "1025:1025"  # SMTP
    profiles: ["dev"]




volumes:
  dbdata:
  uploads:
  # cache and logs removed - they live inside the container image
  extensions:
  artifacts:

