# Stage 1: Builder
FROM registry.infra.mintel.me/mintel/nextjs:v1.8.20 AS base
WORKDIR /app

# Arguments for build-time configuration
ARG NEXT_PUBLIC_BASE_URL
ARG NEXT_PUBLIC_TARGET

# Environment variables for Next.js build
ENV NEXT_PUBLIC_BASE_URL=$NEXT_PUBLIC_BASE_URL
ENV NEXT_PUBLIC_TARGET=$NEXT_PUBLIC_TARGET
ENV SKIP_RUNTIME_ENV_VALIDATION=true
ENV CI=true

# Copy lockfile and manifest for dependency installation caching
COPY package-lock.json package.json .npmrc* ./

# Configure private registry and install dependencies
RUN --mount=type=cache,id=npm,target=/root/.npm \
    --mount=type=secret,id=NPM_TOKEN \
    export NPM_TOKEN=$(cat /run/secrets/NPM_TOKEN) && \
    echo "@mintel:registry=https://git.infra.mintel.me/api/packages/mmintel/npm" > .npmrc && \
    echo "//git.infra.mintel.me/api/packages/mmintel/npm/:_authToken=\${NPM_TOKEN}" >> .npmrc && \
    npm ci && \
    rm .npmrc

# Copy source code
COPY . .

# Stage 2: Development (Hot-Reloading)
FROM base AS development
ENV NODE_ENV=development
CMD ["npm", "run", "dev"]

# Build application
# Stage 3: Builder (Production)
FROM base AS builder
# Limit memory to 1GB to prevent ResourceExhausted in combination with worker limits
ENV NODE_OPTIONS="--max-old-space-size=1024"

# Force Turbopack (Rust/Rayon) and Node.js to use strictly 3 threads to avoid starving the Gitea Runner VPS CPU
ENV RAYON_NUM_THREADS=3
ENV UV_THREADPOOL_SIZE=3

# Build the workspace
RUN npm run build --workspace=apps/website

# Stage 2: Runner
FROM registry.infra.mintel.me/mintel/runtime:v1.8.20 AS runner
WORKDIR /app

# Create nextjs user and group (standardized in runtime image but ensuring local ownership)
USER root
RUN chown -R nextjs:nodejs /app
USER nextjs

ENV HOSTNAME="0.0.0.0"
ENV PORT=3000
ENV NODE_ENV=production

# Copy standalone output and static files
# Since it's a workspace, Next.js output might be in apps/website/.next/standalone
COPY --from=builder --chown=nextjs:nodejs /app/apps/website/public ./apps/website/public
# Next.js standalone mode needs to be enabled in next.config.ts in apps/website
COPY --from=builder --chown=nextjs:nodejs /app/apps/website/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/apps/website/.next/static ./apps/website/.next/static
COPY --from=builder --chown=nextjs:nodejs /app/apps/website/.next/cache ./apps/website/.next/cache

CMD ["node", "apps/website/server.js"]
