# -------------------------------------------------
#  Builder – install deps, compile the Next.js app
# -------------------------------------------------
FROM node:20-alpine AS builder

ARG UID=1001
ARG GID=1001
RUN addgroup -g ${GID} appgroup && \
    adduser -D -u ${UID} -G appgroup appuser

WORKDIR /app
COPY package.json package-lock.json ./

# -------------------------------------------------
#   Install dependencies (deterministic)
# -------------------------------------------------
RUN npm ci               # keep if you have package‑lock.json
# RUN npm install --omit=dev   # uncomment if you don’t have a lockfile

COPY . .
# Next.js produces a `.next` folder and a `public` folder
RUN npm run build        # creates .next, .next/static, etc.

# -------------------------------------------------
#  Runtime – Next.js production server
# -------------------------------------------------
FROM node:20-alpine AS runner
WORKDIR /app

# Copy only the files needed at runtime
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/package*.json ./
# COPY --from=builder /app/next.config.mjs ./
COPY --from=builder /app/next-env.d.ts ./

# Install only production dependencies (no dev deps)
RUN npm ci --omit=dev   # works because lockfile is present; otherwise:
# RUN npm install --omit=dev   # fallback if you have no lockfile

# Expose the port that `next start` uses (default 3000)
EXPOSE 3000

# Pass the backend URL to the client side.
# Next.js reads any env var prefixed with NEXT_PUBLIC_ at build time.
ENV NEXT_PUBLIC_BACKEND_URL=http://regulatory_api:3000

# Start the production server
CMD ["npm", "run", "start"]
