version: "3.9"

services:
  postgres:
    image: postgres:16-alpine
    container_name: uid_postgres
    restart: unless-stopped
    environment:
      POSTGRES_DB: ${POSTGRES_DB:-uid_tracker}
      POSTGRES_USER: ${POSTGRES_USER:-uid_user}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-StrongPass123!}
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - ./database/init.sql:/docker-entrypoint-initdb.d/01_init.sql:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-uid_user}"]
      interval: 10s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine
    container_name: uid_redis
    restart: unless-stopped
    command: >
      redis-server
      --requirepass ${REDIS_PASSWORD:-RedisPass123!}
      --appendonly yes
      --maxmemory 1gb
      --maxmemory-policy allkeys-lru
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD:-RedisPass123!}", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5

  api:
    build:
      context: ./src/UIDTracker.API
      dockerfile: Dockerfile
    container_name: uid_api
    restart: unless-stopped
    ports:
      - "8000:8080"
    environment:
      - ConnectionStrings__Postgres=Host=postgres;Port=5432;Database=${POSTGRES_DB:-uid_tracker};Username=${POSTGRES_USER:-uid_user};Password=${POSTGRES_PASSWORD:-StrongPass123!};Pooling=true;Maximum Pool Size=100;
      - ConnectionStrings__Redis=redis:6379,password=${REDIS_PASSWORD:-RedisPass123!},ssl=false,abortConnect=false
      - TelegramBot__Token=${BOT_TOKEN}
      - TelegramBot__WebhookUrl=${WEBHOOK_URL}
      - TelegramBot__SecretToken=${WEBHOOK_SECRET}
      - Auth__AdminApiKey=${ADMIN_API_KEY}
    volumes:
      - ./logs/api:/app/logs
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy

  worker:
    build:
      context: ./src/UIDTracker.Worker
      dockerfile: Dockerfile
    restart: unless-stopped
    # Use "deploy: replicas: X" to scale workers easily
    deploy:
      replicas: 3
    environment:
      - Redis=redis:6379,password=${REDIS_PASSWORD:-RedisPass123!},ssl=false,abortConnect=false
      - ApiBaseUrl=http://api:8080/
      - ApiKey=${ADMIN_API_KEY}
      - MaxConcurrentJobs=20
      # Để truyền proxy config qua Docker Env, .NET hỗ trợ format mảng dới đây
      - ProxyConfig__Enabled=true
      - ProxyConfig__Urls__0=${PROXY_1:-http://user:pass@1.1.1.1:8080}
      - ProxyConfig__Urls__1=${PROXY_2:-http://user:pass@2.2.2.2:8080}
    volumes:
      - ./logs/worker:/app/logs
    depends_on:
      api:
        condition: service_started

volumes:
  postgres_data:
  redis_data:

networks:
  default:
    name: uid_prod_network
