# Multi-Stage Build: deps → build → runner.
# Analog w-make-com, aber standalone mit bereits gebauter Next.js App.

FROM node:22.13-bookworm-slim AS deps
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends python3 build-essential ca-certificates \
 && rm -rf /var/lib/apt/lists/*
COPY package.json package-lock.json* ./
RUN npm ci

FROM deps AS build
WORKDIR /app
COPY . .
ARG NEXT_PUBLIC_SITE_URL=https://eldov.win
ARG NEXT_PUBLIC_BUILD_HASH=dev
ARG NEXT_PUBLIC_BUILD_DATE=1970-01-01
ENV NEXT_PUBLIC_SITE_URL=${NEXT_PUBLIC_SITE_URL}
ENV NEXT_PUBLIC_BUILD_HASH=${NEXT_PUBLIC_BUILD_HASH}
ENV NEXT_PUBLIC_BUILD_DATE=${NEXT_PUBLIC_BUILD_DATE}
ENV NEXT_TELEMETRY_DISABLED=1
RUN COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "${NEXT_PUBLIC_BUILD_HASH}") && \
    DATE=$(date -u +%Y-%m-%d) && \
    printf 'NEXT_PUBLIC_BUILD_HASH=%s\nNEXT_PUBLIC_BUILD_DATE=%s\n' "${COMMIT}" "${DATE}" > .env.production.local && \
    echo "--- .env.production.local ---" && cat .env.production.local && echo "--- end ---" && \
    npm run build && \
    echo "--- Built. HASH inlined? ---" && \
    grep -o 'NEXT_PUBLIC_BUILD_HASH[^"]*' .next/server/app/[lang]/projects/[slug]/page.js 2>/dev/null | head -1 || true

FROM node:22.13-bookworm-slim AS runner
WORKDIR /app
ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 PORT=3000 HOSTNAME=0.0.0.0
# Non-Root
RUN groupadd --system --gid 1001 nodejs \
 && useradd --system --uid 1001 --gid nodejs eldov
# Standalone-Output (Next.js legt ihn unter .next/standalone an). Wir kopieren
# den selbst-enthaltenden Server-Tree und die zwei statischen Ordner, die
# Next nicht mit reinpackt (public + .next/static).
COPY --from=build --chown=eldov:nodejs /app/.next/standalone ./
COPY --from=build --chown=eldov:nodejs /app/.next/static ./.next/static
COPY --from=build --chown=eldov:nodejs /app/public ./public
RUN mkdir -p /app/data && chown -R eldov:nodejs /app
USER eldov
EXPOSE 3000
CMD ["node", "server.js"]
