FROM node:20-alpine AS builder
USER root
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
WORKDIR /app
ENV PRISMA_SKIP_POSTINSTALL_GENERATE=true
ENV PRISMA_ENGINES_MIRROR=https://registry.npmmirror.com/-/binary/prisma
ENV DISABLE_OPENCOLLECTIVE=1
ENV npm_config_cache=/tmp/npm-cache

# Optional: Use Nexus as npm registry (pass --build-arg NPM_REGISTRY=http://nexus:8081/repository/npm/)
ARG NPM_REGISTRY=
RUN if [ -n "$NPM_REGISTRY" ]; then \
    npm config set registry "$NPM_REGISTRY" && \
    npm config set strict-ssl false && \
    echo "Using npm registry: $NPM_REGISTRY"; \
    fi

COPY package*.json ./
# npm ci: NO proxy so it talks directly to Nexus; no_proxy prevents accidental proxy routing
RUN no_proxy="172.17.0.2,172.17.0.3,localhost,127.0.0.1" \
    NO_PROXY="172.17.0.2,172.17.0.3,localhost,127.0.0.1" \
    DISABLE_OPENCOLLECTIVE=1 \
    PRISMA_SKIP_POSTINSTALL_GENERATE=true \
    npm ci --prefer-offline --no-audit --ignore-scripts
COPY . .
# prisma generate needs internet for engine binary -> use VPN proxy
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 \
    no_proxy="172.17.0.2,172.17.0.3,localhost,127.0.0.1" \
    ./node_modules/.bin/prisma generate && npm run build

FROM node:20-alpine
USER root
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
RUN mkdir -p /app/uploads && chown node:node /app/uploads
WORKDIR /app
COPY --chown=node:node --from=builder /app/package*.json ./
COPY --chown=node:node --from=builder /app/tsconfig.json ./tsconfig.json
COPY --chown=node:node --from=builder /app/node_modules ./node_modules
COPY --chown=node:node --from=builder /app/dist ./dist
COPY --chown=node:node --from=builder /app/prisma ./prisma
COPY --chown=node:node --from=builder /app/prisma/tsconfig.seed.json ./prisma/tsconfig.seed.json
COPY --chown=node:node --from=builder /app/prisma/scientificTerms.ts ./prisma/scientificTerms.ts
EXPOSE 3000
USER node
CMD ["sh", "-c", "npx prisma db push --skip-generate && if [ -f dist/src/main.js ]; then node dist/src/main.js; else node dist/main.js; fi"]
