FROM node:16-slim AS base

# Install dependencies only when needed
FROM base AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apt-get update || : && apt-get install python3 make g++ -y
WORKDIR /app

# Install dependencies based on the preferred package manager
COPY package.json yarn.lock* ./
RUN yarn --frozen-lockfile --ignore-scripts

# Rebuild the source code only when needed
FROM base AS builder
ARG JBD_API_URL
ARG JBD_PORTAL_URL
ENV NEXT_PUBLIC_JBD_API_URL=${JBD_API_URL}
ENV NEXT_PUBLIC_JBD_PORTAL_URL=${JBD_PORTAL_URL}

WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

RUN yarn run build:preview

FROM node:18-slim
WORKDIR /app

# Copy the built app
COPY --from=builder /app/dist/apps/nextjs-preview-app/exported /app/exported
COPY --from=builder /app/apps/nextjs-preview-app/workers-site /app/workers-site

RUN cd /app/workers-site && npm install

EXPOSE 8787

ENTRYPOINT ["npx", "wrangler", "dev", "--site=exported", "--ip=0.0.0.0", "/app/workers-site/index.js"]