# ============================================================
# 🏗️ Stage 1 — Builder
# ============================================================
FROM node:20-alpine AS builder

# Install dependensi dasar
RUN apk add --no-cache git bash build-base curl

WORKDIR /app

# Copy dependencies terlebih dahulu agar cache efisien
COPY package*.json ./

# Pastikan npm up to date agar mendukung flag terbaru
RUN npm install -g npm@11 && npm --version

# Install dependency tanpa devDependencies (aman di semua npm versi)
RUN npm ci --only=production

# Copy seluruh source
COPY . .

# Buat konfigurasi output Next.js
RUN echo "const config = { output: 'export', images: { unoptimized: true } }; export default config;" > next.config.mjs

# Build project (disable Turbopack agar tidak makan RAM)
ENV NEXT_DISABLE_TURBOPACK=1
RUN npx next build && npm cache clean --force

# Siapkan folder static untuk serve
RUN mkdir -p .next/server/app/_next && \
    cp -r .next/static .next/server/app/_next/static && \
    cp -r public/assets .next/server/app/ || true

# ============================================================
# 🧱 Stage 2 — Runtime
# ============================================================
FROM node:20-alpine AS runtime

RUN apk add --no-cache tini && npm install -g serve

WORKDIR /app

COPY --from=builder /app/.next/server/app ./server
COPY --from=builder /app/public ./public

ENV NODE_ENV=production
ENV PORT=3000

EXPOSE 3000
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["serve", "-s", "server", "-l", "3000"]