version: '3.8'

services:
  # ===================================
  # MariaDB Database
  # ===================================
  db:
    image: mariadb:10.11
    container_name: opencrm-db
    restart: unless-stopped
    environment:
      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:-rootpassword}
      MYSQL_DATABASE: ${DB_NAME:-opencrm}
      MYSQL_USER: ${DB_USER:-opencrm}
      MYSQL_PASSWORD: ${DB_PASSWORD:-opencrm123}
    volumes:
      - mariadb_data:/var/lib/mysql
    networks:
      - opencrm-network
    healthcheck:
      test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
      start_period: 10s
      interval: 10s
      timeout: 5s
      retries: 3

  # ===================================
  # OpenCRM Application
  # ===================================
  app:
    build:
      context: ..
      dockerfile: docker/Dockerfile
    container_name: opencrm-app
    restart: unless-stopped
    environment:
      NODE_ENV: production
      PORT: 3001
      DATABASE_URL: mysql://${DB_USER:-opencrm}:${DB_PASSWORD:-opencrm123}@db:3306/${DB_NAME:-opencrm}
      JWT_SECRET: ${JWT_SECRET:?JWT_SECRET is required}
      JWT_EXPIRES_IN: ${JWT_EXPIRES_IN:-7d}
      ENCRYPTION_KEY: ${ENCRYPTION_KEY:?ENCRYPTION_KEY is required}
      RUN_SEED: ${RUN_SEED:-false}
    volumes:
      - uploads_data:/app/uploads
      - backups_data:/app/backups
    networks:
      - opencrm-network
    depends_on:
      db:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:3001/api/health"]
      start_period: 60s
      interval: 30s
      timeout: 10s
      retries: 3

  # ===================================
  # Caddy Reverse Proxy (with auto SSL)
  # ===================================
  caddy:
    image: caddy:2-alpine
    container_name: opencrm-caddy
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro
      - caddy_data:/data
      - caddy_config:/config
    networks:
      - opencrm-network
    depends_on:
      app:
        condition: service_healthy

networks:
  opencrm-network:
    driver: bridge

volumes:
  mariadb_data:
  uploads_data:
  backups_data:
  caddy_data:
  caddy_config:
