# =============================================================================
# ChatApp Frontend - Multi-stage Dockerfile
# Service: Next.js (standalone build) - Port 3001
# Security: non-root user, pinned base, minimal runtime
# ==============================================================================

# ---- Stage 1: Builder ----
FROM node:20-slim@sha256:0a6e0c3e5e9e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e AS builder

WORKDIR /app

# Copy package files and install deps
COPY frontend/package.json frontend/package-lock.json* ./
RUN npm ci --legacy-peer-deps

# Copy frontend source
COPY frontend/ ./

# Set output standalone for minimal runtime image
ENV NEXT_TELEMETRY_DISABLED=1
RUN npm run build

# ---- Stage 2: Runtime ----
FROM node:20-slim@sha256:0a6e0c3e5e9e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e AS runtime

WORKDIR /app

RUN apt-get update && apt-get install -y --no-install-recommends \
    curl dumb-init \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user
RUN groupadd -r nodeapp && useradd -r -g nodeapp -d /app -s /bin/bash nodeapp

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=3001
ENV HOSTNAME=0.0.0.0

# Copy standalone server, static assets, and public directory
COPY --from=builder --chown=nodeapp:nodeapp /app/.next/standalone ./
COPY --from=builder --chown=nodeapp:nodeapp /app/.next/static ./.next/static
COPY --from=builder --chown=nodeapp:nodeapp /app/public ./public

EXPOSE 3001

USER nodeapp

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD curl -f http://localhost:3001/api/health || exit 1

ENTRYPOINT ["dumb-init", "--"]
CMD ["node", "server.js"]