# Stage 1: Build the application
FROM node:18-alpine AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app

# Install dependencies
COPY webapp/package.json webapp/package-lock.json ./
RUN npm ci

# Copy the rest of the application
COPY webapp/ .

# Set environment variables for build
ARG DB_URI
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV DB_URI=${DB_URI}

# Build the application
RUN npm run build

# Stage 2: Create the runner image
FROM node:18-alpine AS runner
WORKDIR /app

# Install dependencies only needed for production
RUN apk add --no-cache dumb-init

# Create a non-root user
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

# Copy the built application from the builder stage
COPY --from=deps /app/next.config.js ./
COPY --from=deps /app/public ./public
COPY --from=deps /app/package.json ./

# Copy the standalone server and static files
COPY --from=deps --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=deps --chown=nextjs:nodejs /app/.next/static ./.next/static

# Set the user to non-root
USER nextjs

# Expose the port the app runs on
EXPOSE 3000

# Set the environment variable for the port
ENV PORT 3000

# Use dumb-init to handle signals properly
ENTRYPOINT ["/usr/bin/dumb-init", "--"]

# Set the command to run the application
CMD ["node", "server.js"]
