version: '3.8'

services:
  n8n:
    image: n8nio/n8n:latest
    container_name: n8n-shared
    restart: unless-stopped
    networks:
      - traefik-public
      - database-internal
      - n8n-shared
    env_file:
      - .env
    environment:
      # General
      N8N_HOST: n8n.ai-impress.com
      N8N_PORT: 5678
      N8N_PROTOCOL: https
      WEBHOOK_URL: https://n8n.ai-impress.com/
      
      # Database
      DB_TYPE: postgresdb
      DB_POSTGRESDB_HOST: postgres-main
      DB_POSTGRESDB_PORT: 5432
      DB_POSTGRESDB_DATABASE: n8n_shared
      DB_POSTGRESDB_USER: n8n_user
      DB_POSTGRESDB_PASSWORD: ${DB_PASSWORD}
      
      # Queue Mode (Redis)
      QUEUE_BULL_REDIS_HOST: redis-main
      QUEUE_BULL_REDIS_PORT: 6379
      QUEUE_BULL_REDIS_PASSWORD: ${REDIS_PASSWORD}
      EXECUTIONS_MODE: queue
      
      # Security
      N8N_BASIC_AUTH_ACTIVE: 'false'
      N8N_ENCRYPTION_KEY: ${N8N_ENCRYPTION_KEY}
      N8N_PAYLOAD_SIZE_MAX: 64
      
      # Timezone
      GENERIC_TIMEZONE: Europe/London
      TZ: Europe/London
      
    volumes:
      - n8n-data:/home/node/.n8n
      - ./custom-nodes:/home/node/.n8n/custom
    labels:
      - "traefik.enable=true"
      
      # Webhook роутер БЕЗ Authelia (для Telegram и других webhooks)
      - "traefik.http.routers.n8n-webhook.rule=Host(`n8n.ai-impress.com`) && (PathPrefix(`/webhook/`) || PathPrefix(`/webhook-test/`))"
      - "traefik.http.routers.n8n-webhook.entrypoints=websecure"
      - "traefik.http.routers.n8n-webhook.tls.certresolver=cloudflare"
      - "traefik.http.routers.n8n-webhook.service=n8n-shared-service"
      - "traefik.http.routers.n8n-webhook.priority=200"
      
      # OAuth роутер БЕЗ Authelia (для предотвращения ошибки 431)
      - "traefik.http.routers.n8n-oauth.rule=Host(`n8n.ai-impress.com`) && PathPrefix(`/rest/oauth`)"
      - "traefik.http.routers.n8n-oauth.entrypoints=websecure"
      - "traefik.http.routers.n8n-oauth.tls.certresolver=cloudflare"
      - "traefik.http.routers.n8n-oauth.service=n8n-shared-service"
      - "traefik.http.routers.n8n-oauth.priority=150"
      
      # Основной роутер с Authelia (для UI)
      - "traefik.http.routers.n8n-shared.rule=Host(`n8n.ai-impress.com`)"
      - "traefik.http.routers.n8n-shared.entrypoints=websecure"
      - "traefik.http.routers.n8n-shared.tls.certresolver=cloudflare"
      - "traefik.http.routers.n8n-shared.middlewares=authelia@file"
      - "traefik.http.routers.n8n-shared.service=n8n-shared-service"
      - "traefik.http.routers.n8n-shared.priority=50"
      
      # Сервис
      - "traefik.http.services.n8n-shared-service.loadbalancer.server.port=5678"

volumes:
  n8n-data:

networks:
  traefik-public:
    external: true
  database-internal:
    external: true
  n8n-shared:
    external: true
