services:
  # Lightweight proxy: gives Caddy the labels to route klz.localhost → host Mac
  klz-proxy:
    image: alpine:latest
    command: sleep infinity
    restart: unless-stopped
    networks:
      - infra
    labels:
      - "caddy=http://${TRAEFIK_HOST:-klz.localhost}"
      - "caddy.reverse_proxy=host.docker.internal:3100"

  # Full Docker dev (use with `pnpm run dev:docker`)
  klz-app:
    build:
      context: .
      dockerfile: Dockerfile.dev
    working_dir: /app
    restart: unless-stopped
    networks:
      default:
      infra:
        aliases:
          - klz.localhost
    env_file:
      - ${ENV_FILE:-.env}
    environment:
      NODE_ENV: development
      NEXT_TELEMETRY_DISABLED: "1"
      POSTGRES_URI: postgres://${PAYLOAD_DB_USER:-payload}:${PAYLOAD_DB_PASSWORD:-120in09oenaoinsd9iaidon}@klz-db:5432/${PAYLOAD_DB_NAME:-payload}
      PAYLOAD_SECRET: ${PAYLOAD_SECRET:-fallback-secret-for-dev}
      NODE_OPTIONS: "--max-old-space-size=4096"
      UV_THREADPOOL_SIZE: "4"
      NPM_TOKEN: ${NPM_TOKEN:-}
      CI: "true"
    volumes:
      - .:/app
      - klz_node_modules:/app/node_modules
      - klz_next_cache:/app/.next
      - klz_turbo_cache:/app/.turbo
      - klz_pnpm_store:/pnpm
      - /app/.git
      - /app/reference
      - /app/data
    deploy:
      resources:
        limits:
          cpus: '4'
          memory: 8G
    command: >
      sh -c "pnpm install && pnpm next dev --webpack --hostname 0.0.0.0"
    labels:
      - "traefik.enable=true"
      - "traefik.http.services.${PROJECT_NAME:-klz}-app-svc.loadbalancer.server.port=3000"
      - "traefik.docker.network=infra"
      - "caddy=http://${TRAEFIK_HOST:-klz.localhost}"
      - "caddy.reverse_proxy={{upstreams 3000}}"

  klz-db:
    image: postgres:15-alpine
    restart: unless-stopped
    env_file:
      - ${ENV_FILE:-.env}
    environment:
      POSTGRES_DB: ${PAYLOAD_DB_NAME:-payload}
      POSTGRES_USER: ${PAYLOAD_DB_USER:-payload}
      POSTGRES_PASSWORD: ${PAYLOAD_DB_PASSWORD:-120in09oenaoinsd9iaidon}
      # Docker Desktop on Mac routes host connections via external IP, not 127.0.0.1.
      # Without this, pg_hba.conf rejects the connection as "no encryption".
      POSTGRES_HOST_AUTH_METHOD: trust
    volumes:
      - klz_db_data:/var/lib/postgresql/data
    networks:
      - default
    ports:
      - "54322:5432"

networks:
  default:
    name: ${PROJECT_NAME:-klz-cables}-internal
  infra:
    external: true

volumes:
  klz_db_data:
    external: false
  klz_node_modules:
  klz_next_cache:
  klz_turbo_cache:
  klz_pnpm_store:
