# Stage 1: Building the code
FROM node:20-bookworm-slim AS frontend-builder

WORKDIR /app

# Install dependencies needed for build
# (Using --frozen-lockfile is safer for reproducible builds, but requires package-lock.json)
COPY package.json package-lock.json* ./
RUN npm ci || npm install

# Copy source code
COPY . .

# Set API URL to empty - all API calls go through Next.js rewrites proxy
ARG NEXT_PUBLIC_API_URL=
ENV NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL}
ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_OPTIONS="--max-old-space-size=2048"
ENV NEXT_PRIVATE_SWC_MAX_CONCURRENCY=1
ENV NEXT_BUILD_CONCURRENCY=1

# Build the application
RUN npm run build

# Stage 2: Production image
FROM node:20-bookworm-slim AS runner

WORKDIR /app

ENV NODE_ENV=production

# Don't run as root
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

# Copy necessary files from builder
COPY --from=frontend-builder /app/next.config.ts ./
COPY --from=frontend-builder /app/public ./public
COPY --from=frontend-builder /app/.next/static ./.next/static

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=frontend-builder --chown=nextjs:nodejs /app/.next/standalone ./

USER nextjs

EXPOSE 3000

ENV PORT 3000
# set hostname to localhost
ENV HOSTNAME "0.0.0.0"

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