# ===== 构建阶段 =====
FROM node:18.20.6 AS builder

# 安装指定版本的 npm 和 pm2
RUN npm install -g npm@10.8.2 \
    && npm install -g pm2@5.4.3

WORKDIR /app

# 拷贝依赖文件并安装生产依赖
COPY package.json package-lock.json ./
RUN npm ci

# 拷贝全部源码
COPY . .

# 构建项目
RUN npm run build


# ===== 运行阶段 =====
FROM node:18.20.6 AS runner

# 安装指定版本的 npm 和 pm2
RUN npm install -g npm@10.8.2 \
    && npm install -g pm2@5.4.3

WORKDIR /app

# 拷贝依赖声明并安装仅生产依赖
# COPY package.json package-lock.json ./
# RUN npm ci --omit=dev

# 拷贝构建产物和依赖
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json

# 环境变量与端口
ENV NODE_ENV=production
EXPOSE 3000

# 正确使用 pm2-runtime 保持容器挂起
CMD ["pm2-runtime", "start", "npm", "--name", "chatai-ui", "--", "run", "start"]
