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

WORKDIR /app

# Copy các file cấu hình dependency
COPY package*.json ./

# Cài đặt mọi thư viện (bao gồm cả devDependencies để build)
RUN npm ci --legacy-peer-deps

# Copy toàn bộ source code và build dự án
COPY . .
ENV NODE_OPTIONS=--max-old-space-size=8192
RUN npm run build

# --- STAGE 2---
FROM node:20-alpine AS runner

WORKDIR /app

# Thiết lập môi trường Production
ENV NODE_ENV=production

# 1. Cài đặt PM2 toàn cục và dọn dẹp cache của npm ngay lập tức
RUN npm install pm2 -g && npm cache clean --force

# 2. Chỉ copy những file cần thiết nhất từ stage builder
# Nuxt 3/Nitro đã đóng gói mọi node_modules cần thiết vào .output
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"]