# syntax=docker/dockerfile:1

# ─── Stage 1: install deps ────────────────────────────────────────────────────
FROM node:22-alpine AS deps
WORKDIR /app
RUN apk add --no-cache libc6-compat \
 && corepack enable \
 && corepack prepare pnpm@latest --activate
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile

# ─── Stage 2: build ───────────────────────────────────────────────────────────
FROM node:22-alpine AS builder
WORKDIR /app
RUN apk add --no-cache libc6-compat \
 && corepack enable \
 && corepack prepare pnpm@latest --activate
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Build-time placeholders — real values injected at runtime.
# Payload reads env during `next build` (import map / type generation), so these
# must parse but never need to resolve.
ENV NEXT_TELEMETRY_DISABLED=1
ENV PAYLOAD_SECRET=build-time-placeholder
ENV DATABASE_URL=postgres://placeholder:placeholder@localhost:5432/placeholder
ENV STRIPE_SECRET_KEY=sk_test_abcdefghijklmnopqrstuvwxyz1234567890
ENV NEXT_PUBLIC_SERVER_URL=https://rebours.studio

RUN pnpm build

# Trim dev deps to shrink the runtime image
RUN pnpm prune --prod

# ─── Stage 3: runtime ─────────────────────────────────────────────────────────
FROM node:22-alpine AS runtime
WORKDIR /app
RUN apk add --no-cache libc6-compat

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

# Non-root user for the runtime
RUN addgroup --system --gid 1001 nodejs \
 && adduser  --system --uid 1001 nextjs

COPY --from=builder --chown=nextjs:nodejs /app/.next            ./.next
COPY --from=builder --chown=nextjs:nodejs /app/public           ./public
COPY --from=builder --chown=nextjs:nodejs /app/node_modules     ./node_modules
COPY --from=builder --chown=nextjs:nodejs /app/package.json     ./package.json
COPY --from=builder --chown=nextjs:nodejs /app/next.config.mjs  ./next.config.mjs
COPY --from=builder --chown=nextjs:nodejs /app/src              ./src
COPY --from=builder --chown=nextjs:nodejs /app/tsconfig.json    ./tsconfig.json

# Media uploads live on a mounted volume in K8s; create the dir so Payload can write to it
RUN mkdir -p /app/media && chown -R nextjs:nodejs /app/media

USER nextjs
EXPOSE 3000

# Run pending migrations (idempotent) then start Next.js
CMD ["sh", "-c", "node node_modules/payload/bin.js migrate && node node_modules/next/dist/bin/next start"]
