FROM node:24-alpine

WORKDIR /app

# Install pnpm as upstream requires
RUN corepack enable && corepack prepare pnpm@10.14.0 --activate

COPY package.json pnpm-lock.yaml ./

# Install dependencies from lockfile (pins SDK to upstream-compatible version)
RUN pnpm install --frozen-lockfile

COPY . .

RUN pnpm build

# Entrypoint script converts env vars to CLI args (profile JSON file)
RUN cat <<'ENTRYEOF' > /docker-entrypoint.sh
#!/bin/sh
set -e
if [ -n "${DISCOURSE_URL}" ] && [ -n "${DISCOURSE_API_KEY}" ]; then
  echo -n '{"auth_pairs":[{"site":"' > /tmp/profile.json
  echo -n "${DISCOURSE_URL}" >> /tmp/profile.json
  echo -n '","api_key":"' >> /tmp/profile.json
  echo -n "${DISCOURSE_API_KEY}" >> /tmp/profile.json
  echo -n '"' >> /tmp/profile.json
  if [ -n "${DISCOURSE_API_USERNAME}" ]; then
    echo -n ',"api_username":"' >> /tmp/profile.json
    echo -n "${DISCOURSE_API_USERNAME}" >> /tmp/profile.json
    echo -n '"' >> /tmp/profile.json
  fi
  echo -n '}]}' >> /tmp/profile.json
  exec node dist/index.js --profile /tmp/profile.json --site "${DISCOURSE_URL}" --allow-writes --read-only false "$@"
else
  exec node dist/index.js "$@"
fi
ENTRYEOF
RUN chmod +x /docker-entrypoint.sh

ENTRYPOINT ["/docker-entrypoint.sh"]
