# --- STAGE 1: Build (Môi trường build) ---
FROM node:20-alpine AS builder
WORKDIR /app

# Tăng memory limit ngay từ đầu
ENV NODE_OPTIONS="--max-old-space-size=8192"

# Copy package files trước
COPY package*.json ./

# Cài dependencies
RUN npm ci --legacy-peer-deps

# Copy source code
COPY . .

# Build với memory limit rõ ràng
RUN npm run build

# --- STAGE 2: Production ---
FROM node:20-alpine AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV NODE_OPTIONS="--max-old-space-size=2048"

# Cài PM2
RUN npm install pm2 -g && npm cache clean --force

# Copy những file cần thiết từ builder
COPY --from=builder /app/.output ./.output
COPY --from=builder /app/ecosystem.config.cjs ./
COPY --from=builder /app/package*.json ./

EXPOSE 3000

CMD ["pm2-runtime", "ecosystem.config.cjs"]