# =============================================================================
# Customer Portal - Portainer Stack (Bridge Network Mode)
# =============================================================================
# Uses Docker's default bridge network to avoid iptables issues
# All env vars passed via Portainer UI
# =============================================================================

services:
  # ---------------------------------------------------------------------------
  # Frontend (Next.js)
  # ---------------------------------------------------------------------------
  frontend:
    image: ${FRONTEND_IMAGE:-portal-frontend}:${IMAGE_TAG:-latest}
    container_name: portal-frontend
    ports:
      - "127.0.0.1:${FRONTEND_PORT:-3000}:3000"
    environment:
      - NODE_ENV=production
      - PORT=3000
      - HOSTNAME=0.0.0.0
    restart: unless-stopped
    depends_on:
      - backend
    network_mode: bridge
    links:
      - backend
    healthcheck:
      test:
        [
          "CMD",
          "node",
          "-e",
          "fetch('http://localhost:3000/_health').then(r=>r.ok||process.exit(1)).catch(()=>process.exit(1))",
        ]
      interval: 30s
      timeout: 10s
      start_period: 40s
      retries: 3

  # ---------------------------------------------------------------------------
  # Backend (NestJS BFF)
  # ---------------------------------------------------------------------------
  backend:
    image: ${BACKEND_IMAGE:-portal-backend}:${IMAGE_TAG:-latest}
    container_name: portal-backend
    ports:
      - "127.0.0.1:${BACKEND_PORT:-4000}:4000"
    environment:
      # Core
      - NODE_ENV=production
      - APP_NAME=${APP_NAME:-customer-portal-bff}
      - APP_BASE_URL=${APP_BASE_URL}
      - BFF_PORT=4000
      - PORT=4000

      # Database - use "database" as host (via links)
      - DATABASE_URL=postgresql://${POSTGRES_USER:-portal}:${POSTGRES_PASSWORD}@database:5432/${POSTGRES_DB:-portal_prod}?schema=public

      # Redis - use "cache" as host (via links)
      - REDIS_URL=redis://cache:6379/0

      # Security
      - JWT_SECRET=${JWT_SECRET}
      - JWT_EXPIRES_IN=${JWT_EXPIRES_IN:-7d}
      - JWT_SECRET_PREVIOUS=${JWT_SECRET_PREVIOUS}
      - JWT_ISSUER=${JWT_ISSUER}
      - JWT_AUDIENCE=${JWT_AUDIENCE}
      - BCRYPT_ROUNDS=${BCRYPT_ROUNDS:-12}
      - CORS_ORIGIN=${CORS_ORIGIN}
      - TRUST_PROXY=true
      - CSRF_SECRET_KEY=${CSRF_SECRET_KEY}

      # Auth
      - AUTH_ALLOW_REDIS_TOKEN_FAILOPEN=${AUTH_ALLOW_REDIS_TOKEN_FAILOPEN:-false}
      - AUTH_REQUIRE_REDIS_FOR_TOKENS=${AUTH_REQUIRE_REDIS_FOR_TOKENS:-false}
      - AUTH_BLACKLIST_FAIL_CLOSED=${AUTH_BLACKLIST_FAIL_CLOSED:-false}
      - AUTH_MAINTENANCE_MODE=${AUTH_MAINTENANCE_MODE:-false}

      # Rate Limiting
      - RATE_LIMIT_TTL=${RATE_LIMIT_TTL:-60}
      - RATE_LIMIT_LIMIT=${RATE_LIMIT_LIMIT:-100}
      - EXPOSE_VALIDATION_ERRORS=false

      # WHMCS
      - WHMCS_BASE_URL=${WHMCS_BASE_URL}
      - WHMCS_API_IDENTIFIER=${WHMCS_API_IDENTIFIER}
      - WHMCS_API_SECRET=${WHMCS_API_SECRET}

      # Salesforce
      - SF_LOGIN_URL=${SF_LOGIN_URL}
      - SF_CLIENT_ID=${SF_CLIENT_ID}
      - SF_USERNAME=${SF_USERNAME}
      - SF_EVENTS_ENABLED=${SF_EVENTS_ENABLED:-true}
      - SF_PRIVATE_KEY_BASE64=${SF_PRIVATE_KEY_BASE64}
      - SF_PRIVATE_KEY_PATH=/app/secrets/sf-private.key

      # Freebit
      - FREEBIT_BASE_URL=${FREEBIT_BASE_URL:-https://i1.mvno.net/emptool/api}
      - FREEBIT_OEM_ID=${FREEBIT_OEM_ID:-PASI}
      - FREEBIT_OEM_KEY=${FREEBIT_OEM_KEY}

      # Japan Post (Address Lookup)
      - JAPAN_POST_API_URL=${JAPAN_POST_API_URL}
      - JAPAN_POST_CLIENT_ID=${JAPAN_POST_CLIENT_ID}
      - JAPAN_POST_CLIENT_SECRET=${JAPAN_POST_CLIENT_SECRET}

      # Email
      - EMAIL_ENABLED=${EMAIL_ENABLED:-true}
      - EMAIL_FROM=${EMAIL_FROM:-no-reply@asolutions.jp}
      - EMAIL_FROM_NAME=${EMAIL_FROM_NAME:-Assist Solutions}
      - SENDGRID_API_KEY=${SENDGRID_API_KEY}

      # Portal
      - PORTAL_PRICEBOOK_ID=${PORTAL_PRICEBOOK_ID}
      - PORTAL_PRICEBOOK_NAME=${PORTAL_PRICEBOOK_NAME:-Portal}

      # Logging
      - LOG_LEVEL=${LOG_LEVEL:-info}

      # Enable automatic database migrations on startup
      - RUN_MIGRATIONS=true
    restart: unless-stopped
    depends_on:
      - database
      - cache
    network_mode: bridge
    links:
      - database
      - cache
    # Uses the built-in entrypoint which handles:
    # - SF key decoding from SF_PRIVATE_KEY_BASE64
    # - Database migration when RUN_MIGRATIONS=true
    # - Waiting for dependencies (nc checks in entrypoint)
    healthcheck:
      test:
        [
          "CMD",
          "node",
          "-e",
          "fetch('http://localhost:4000/health').then(r=>r.ok||process.exit(1)).catch(()=>process.exit(1))",
        ]
      interval: 30s
      timeout: 10s
      start_period: 60s
      retries: 3

  # ---------------------------------------------------------------------------
  # PostgreSQL Database
  # ---------------------------------------------------------------------------
  database:
    image: postgres:17-alpine
    container_name: portal-database
    environment:
      - POSTGRES_DB=${POSTGRES_DB:-portal_prod}
      - POSTGRES_USER=${POSTGRES_USER:-portal}
      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
      - POSTGRES_INITDB_ARGS=--encoding=UTF-8 --lc-collate=C --lc-ctype=C
    volumes:
      - postgres_data:/var/lib/postgresql/data
    restart: unless-stopped
    network_mode: bridge
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-portal} -d ${POSTGRES_DB:-portal_prod}"]
      interval: 10s
      timeout: 5s
      start_period: 30s
      retries: 5

  # ---------------------------------------------------------------------------
  # Redis Cache
  # ---------------------------------------------------------------------------
  cache:
    image: redis:7-alpine
    container_name: portal-cache
    command:
      [
        "redis-server",
        "--save",
        "60",
        "1",
        "--loglevel",
        "warning",
        "--maxmemory",
        "256mb",
        "--maxmemory-policy",
        "noeviction",
      ]
    volumes:
      - redis_data:/data
    restart: unless-stopped
    network_mode: bridge
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  postgres_data:
    driver: local
  redis_data:
    driver: local
