# syntax=docker/dockerfile:1

# =============================================================================
# Jenado Unlimited Website - Production Dockerfile
# Multi-stage build for a minimal, secure production image.
# =============================================================================

# ---- Base image with Node (Alpine for small footprint) ------------------------
FROM node:22-alpine AS base

# Install system dependencies needed for sharp (image optimization) and healthchecks
RUN apk add --no-cache libc6-compat wget

WORKDIR /app

# Enable corepack for pnpm (matches lockfileVersion 9)
RUN corepack enable

# ---- Dependencies stage -------------------------------------------------------
FROM base AS deps

# Copy only manifests for better layer caching
COPY package.json pnpm-lock.yaml ./
COPY pnpm-workspace.yaml ./

# Install dependencies (frozen for reproducibility)
RUN pnpm install --frozen-lockfile

# ---- Builder stage ------------------------------------------------------------
FROM base AS builder

# Bring in dependencies
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Build the Next.js app (uses output: "standalone" from next.config.ts)
ENV NEXT_TELEMETRY_DISABLED=1
RUN pnpm build

# ---- Runner stage (minimal production image) ----------------------------------
FROM base AS runner

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
# Default port (can be overridden at runtime)
ENV PORT=3000

# Create a non-root user for security
RUN addgroup --system --gid 1001 nodejs \
  && adduser --system --uid 1001 nextjs

WORKDIR /app

# Copy public assets
COPY --from=builder /app/public ./public

# Copy standalone output (contains a minimal server.js + required node_modules)
# See: https://nextjs.org/docs/app/api-reference/next-config-js/output
COPY --from=builder /app/.next/standalone ./

# Copy static assets into the correct location relative to server.js
COPY --from=builder /app/.next/static ./.next/static

# Ensure correct ownership
RUN chown -R nextjs:nodejs /app

USER nextjs

EXPOSE 3000

# Basic healthcheck using the /api/health endpoint
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD wget -qO- http://127.0.0.1:${PORT}/api/health || exit 1

# Start the standalone server
CMD ["node", "server.js"]
