# CI can pass a Gitea-hosted mirror when Docker Hub TLS fails (see ci-resolve-node-image.ps1).
ARG NODE_IMAGE=node:20-alpine

# Build stage — produces `.next/standalone` (see next.config.ts output: standalone)
FROM ${NODE_IMAGE} AS builder

WORKDIR /app

COPY package*.json ./
# Same safeguard as backend: incomplete npm ci can leave node_modules/.bin empty.
RUN npm ci --no-audit --no-fund || true; \
    if [ ! -e node_modules/.bin/next ]; then \
      echo "Incomplete npm ci (missing .bin links) — falling back to npm install"; \
      rm -rf node_modules; \
      npm install --no-audit --no-fund; \
    fi; \
    test -e node_modules/.bin/next

COPY . .

ARG NEXT_PUBLIC_API_URL
ARG NEXT_PUBLIC_APP_URL
ARG NEXT_PUBLIC_APP_NAME
ARG NEXT_PUBLIC_SENTRY_DSN
ARG NEXT_PUBLIC_SENTRY_ENVIRONMENT

ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_ENV=production
ENV NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL}
ENV NEXT_PUBLIC_APP_URL=${NEXT_PUBLIC_APP_URL}
ENV NEXT_PUBLIC_APP_NAME=${NEXT_PUBLIC_APP_NAME}
ENV NEXT_PUBLIC_SENTRY_DSN=${NEXT_PUBLIC_SENTRY_DSN}
ENV NEXT_PUBLIC_SENTRY_ENVIRONMENT=${NEXT_PUBLIC_SENTRY_ENVIRONMENT}

RUN npm run build

# Production — minimal runtime using Next.js standalone bundle
FROM ${NODE_IMAGE} AS runner

RUN apk add --no-cache dumb-init

WORKDIR /app

RUN addgroup -g 1001 -S nodejs && \
    adduser -S dyolink -u 1001

ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME=0.0.0.0

COPY --from=builder --chown=dyolink:nodejs /app/.next/standalone ./
COPY --from=builder --chown=dyolink:nodejs /app/.next/static ./.next/static
# Standalone does not include public/; catalog icons are <img src="/prosthesis-catalog/*.svg">.
COPY --from=builder --chown=dyolink:nodejs /app/public ./public

COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
# Windows git/build context may use CRLF; strip before chmod (fixes dumb-init "No such file or directory").
RUN sed -i 's/\r$//' /usr/local/bin/docker-entrypoint.sh && chmod +x /usr/local/bin/docker-entrypoint.sh

USER dyolink

EXPOSE 3000

HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \
  CMD node -e "require('http').get('http://127.0.0.1:3000/', (r) => { process.exit(r.statusCode >= 200 && r.statusCode < 400 ? 0 : 1); }).on('error', () => process.exit(1))"

ENTRYPOINT ["dumb-init", "--", "docker-entrypoint.sh"]

CMD ["node", "server.js"]
