# syntax=docker/dockerfile:1

# ---- Build stage ----
ARG NODE_VERSION=20
FROM node:${NODE_VERSION}-slim AS builder
WORKDIR /app

ENV NEXT_TELEMETRY_DISABLED=1

# Build-time public env hook
ARG NEXT_PUBLIC_FASTAPI_URL
ENV NEXT_PUBLIC_FASTAPI_URL=${NEXT_PUBLIC_FASTAPI_URL}

# 1) Install deps with caching
COPY package.json package-lock.json* ./
RUN npm ci

# 2) Copy source
COPY . .

# 3) Generate Prisma client (safe no-op if unused)
RUN npx prisma generate || true

# 4) Build Next.js (requires next.config.js => output: 'standalone')
RUN npm run build

# ---- Runtime stage ----
FROM node:${NODE_VERSION}-slim AS runner
WORKDIR /app

ENV NODE_ENV=production \
    NEXT_TELEMETRY_DISABLED=1 \
    HOSTNAME=0.0.0.0 \
    PORT=3005

# Minimal server & assets
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
COPY --from=builder /app/prisma ./prisma

# Optional (only if Prisma engine errors show up):
# COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
# COPY --from=builder /app/node_modules/@prisma ./node_modules/@prisma

USER node
EXPOSE 3005

# (Optional) healthcheck
# HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
#   CMD node -e "require('http').get('http://127.0.0.1:'+(process.env.PORT||3005)+'/_next/static/webpack/')"

CMD ["node", "server.js"]

