# Build stage — produces `.next/standalone` (see next.config.ts output: standalone)
FROM node:20-alpine 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

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}

RUN npm run build

# Production — minimal runtime using Next.js standalone bundle
FROM node:20-alpine 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

COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN 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) => {if(r.statusCode!==200)process.exit(1)})"

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

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