# Stage 0: Development (bind-mount source, run next dev).
FROM node:22-alpine AS development
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci || npm install
COPY . .
EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
ENV NODE_ENV=development
# WATCHPACK_POLLING helps with bind mounts on some file systems.
ENV WATCHPACK_POLLING=true
ENTRYPOINT ["sh", "-c", "[ -d node_modules/.bin ] || npm install; exec npm run dev"]

# Stage 1: Install dependencies.
FROM node:22-alpine AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci || npm install

# Stage 2: Build the application.
FROM node:22-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Build arguments for environment variables needed at build time.
ARG NEXT_PUBLIC_DRUPAL_BASE_URL
ARG DRUPAL_CLIENT_ID
ARG DRUPAL_CLIENT_SECRET
ARG DRUPAL_OAUTH_SCOPE
ENV NEXT_PUBLIC_DRUPAL_BASE_URL=${NEXT_PUBLIC_DRUPAL_BASE_URL}
ENV DRUPAL_CLIENT_ID=${DRUPAL_CLIENT_ID}
ENV DRUPAL_CLIENT_SECRET=${DRUPAL_CLIENT_SECRET}
ENV DRUPAL_OAUTH_SCOPE=${DRUPAL_OAUTH_SCOPE}

RUN npm run build

# Stage 3: Production runner.
FROM node:22-alpine AS runner
WORKDIR /app

ENV NODE_ENV=production

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

# Copy standalone output.
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"

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