#
# FRONTEND DOCKERFILE
#
# Multi-stage image for the Next.js SPA/SSR frontend.
# - runner: production server with minimal footprint
# - builder: compiles the Next.js app
# - dev: hot-reload friendly image
#
# COMPOSE_PROFILES decides which stage is used by docker-compose.yml.
#

FROM node:22-slim AS base
WORKDIR /app

ENV NPM_CONFIG_LOGLEVEL=warn \
    NODE_OPTIONS="--enable-source-maps"

# ------------------------------------------------------------------------------
# Dependencies cache
# ------------------------------------------------------------------------------
FROM base AS deps
COPY package.json package-lock.json* ./
RUN npm ci

# ------------------------------------------------------------------------------
# Production dependencies only (pruned to omit dev tooling)
# ------------------------------------------------------------------------------
FROM base AS prod-deps
COPY package.json package-lock.json* ./
RUN npm ci --omit=dev

# ------------------------------------------------------------------------------
# Builder: compile the application for production
# ------------------------------------------------------------------------------
FROM base AS builder

COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NODE_ENV=production
RUN npm run build

# ------------------------------------------------------------------------------
# Production runner: serve the built Next.js app
# ------------------------------------------------------------------------------
FROM node:22-slim AS runner
WORKDIR /app

ENV NODE_ENV=production \
    NEXT_TELEMETRY_DISABLED=1

USER node
COPY --from=prod-deps --chown=node:node /app/node_modules ./node_modules
COPY --from=builder --chown=node:node /app/.next ./.next
COPY --from=builder --chown=node:node /app/public ./public
COPY --from=builder --chown=node:node /app/package.json ./package.json

EXPOSE 3000
CMD ["npm", "run", "start"]

# ------------------------------------------------------------------------------
# Development: keeps node_modules and sources mounted for hot reload
# ------------------------------------------------------------------------------
FROM deps AS dev
WORKDIR /app

ENV NODE_ENV=development \
    NEXT_TELEMETRY_DISABLED=1

USER node
EXPOSE 3000
CMD ["npm", "run", "dev", "--", "--hostname", "0.0.0.0", "--port", "3000"]
