# ============================================================================
# DOCKER COMPOSE - STAGING ENVIRONMENT
# ============================================================================
# IDÊNTICO ao production, EXCETO:
#   - SEM nginx (staging usa porta direta do app)
#   - SEM certbot (sem SSL em staging)
#   - SEM cron (tarefas agendadas apenas em production)
# ============================================================================

# Nome do projeto explícito (evita problemas com symlinks)
name: medoracle-staging

x-logging: &default-logging
  driver: "json-file"
  options:
    max-size: "10m"
    max-file: "3"

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

    depends_on:
      migrate:
        condition: service_completed_successfully
    environment:
      ENVIRONMENT: ${ENVIRONMENT:-staging}
      DEBUG: ${DEBUG:-false}
      HMR: ${HMR:-0}
      APP_URL: ${APP_URL}
      DB_DRIVER: ${DB_DRIVER:-mysql}
      DB_HOST: ${DB_HOST:-db}
      DB_PORT: ${DB_PORT:-3306}
      DB_NAME: ${DB_NAME}
      DB_TUSS_NAME: ${DB_TUSS_NAME:-medclub_tuss}
      DB_USER: ${DB_USER}
      DB_PASSWORD: ${DB_PASSWORD}
    logging: *default-logging
    volumes:
      - ./public/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
      # Mount .env to allow runtime configuration changes via admin panel
      - ./.env:/var/www/html/.env
      # Mount registry.json to allow runtime configuration without rebuild
      - ./config/registry.json:/var/www/html/config/registry.json:ro
    # Ports removed - accessed via Nginx
    # ports:
    #   - "${APP_HTTP_PORT:-8080}:80"
    healthcheck:
      test: [ "CMD-SHELL", "curl -f http://localhost/health.php || exit 1" ]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 30s
    restart: unless-stopped

  migrate:
    image: medoracle-staging-app:latest
    container_name: medoracle-staging-migrate
    working_dir: /var/www/html
    depends_on:
      db:
        condition: service_healthy
    volumes:
      # Mount registry.json for migrations that may need model configuration
      - ./config/registry.json:/var/www/html/config/registry.json:ro
    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 (usando ROOT)...'
        max_attempts=30
        attempt=0
        until php -r '$$h=getenv("DB_HOST");$$P=getenv("DB_PORT")?:3306;$$p=getenv("DB_PASSWORD");$$n=getenv("DB_NAME");try{$$pdo=new PDO("mysql:host=$$h;port=$$P;dbname=$$n","root",$$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 com usuário ROOT...'
        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}
      APP_URL: ${APP_URL}
      DB_DRIVER: ${DB_DRIVER}
      DB_HOST: ${DB_HOST}
      DB_PORT: ${DB_PORT}
      DB_NAME: ${DB_NAME}
      DB_TUSS_NAME: ${DB_TUSS_NAME:-medclub_tuss}
      # IMPORTANTE: Usar ROOT para migrations (permite criar segundo banco)
      DB_USER: root
      DB_PASSWORD: ${DB_ROOT_PASSWORD}
    restart: "no"
    logging: *default-logging

  # CRON removido - apenas em production

  # NGINX - Staging (HTTP Only + Maintenance Page)
  nginx:
    image: nginx:alpine
    container_name: medoracle-staging-nginx
    ports:
      - "${APP_HTTP_PORT:-8080}:80"
    volumes:
      - ./nginx/nginx.staging.conf:/etc/nginx/conf.d/default.conf:ro
      - ./nginx/maintenance.html:/usr/share/nginx/html/maintenance.html:ro
      - ./nginx/.htpasswd:/etc/nginx/.htpasswd:ro # HTTP Basic Auth (Staging only)
      # Volume compartilhado para flag de manutenção (se necessário persistir)
      # - maintenance-data:/usr/share/nginx/html
    depends_on:
      app:
        condition: service_started # Não espera healthy para poder mostrar erro 502 se app cair
    healthcheck:
      test: [ "CMD-SHELL", "wget --no-verbose --tries=1 -O /dev/null http://localhost:80/health.php || exit 0" ] # Exit 0 pois pode estar em manutenção
      interval: 30s
      timeout: 10s
      retries: 3
    restart: unless-stopped
    logging: *default-logging

  db:
    image: mysql:8.0
    container_name: medoracle-staging-db
    environment:
      MYSQL_DATABASE: ${DB_NAME}
      MYSQL_USER: ${DB_USER}
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
      # Segundo banco (TUSS) será criado pela migration
      # ports:
      # - "3306:3306"  # Commented out to avoid conflicts in production
    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:
      - medoracle-staging-db-data:/var/lib/mysql
    restart: unless-stopped
    logging: *default-logging

  # PHPMyAdmin for database management (staging/production)
  # SECURITY: Requires manual login - no auto-authentication
  phpmyadmin:
    image: phpmyadmin:latest
    container_name: medoracle-staging-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
    logging: *default-logging
    # profiles: [ "admin" ]  # Comentado para subir sempre

    # NGINX removido - staging não usa proxy reverso

    # CERTBOT removido - staging não usa SSL

    # 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:
  medoracle-staging-db-data:
  medoracle-staging-cache:
  medoracle-staging-logs:
  uploads:
  extensions:
  artifacts:
