# 阶段1: 构建阶段
FROM node:22.14.0-bookworm AS builder

WORKDIR /app

# 2. 复制依赖文件（优先层）
COPY package.json package-lock.json ./
# RUN npm ci --legacy-peer-deps
RUN npm install --legacy-peer-deps

# 3. 复制源码并构建
COPY . .
RUN npm run build

# 阶段2: 生产运行阶段
FROM node:22.14.0-bookworm-slim

WORKDIR /app

# 1. 生产环境配置
ENV NODE_ENV production
ENV NEXT_TELEPORT_DISABLED 1
ENV PORT 3000

# 2. 从构建阶段复制文件
COPY --from=builder /app/package.json .
COPY --from=builder /app/package-lock.json .
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/next.config.js ./  # 如果有

# 3. 如果是自定义服务器需要复制
# COPY --from=builder /app/server ./server

# 4. 非root用户
RUN groupadd -g 1001 nodejs && \
    useradd -u 1001 -g nodejs -d /app nodejs && \
    chown -R nodejs:nodejs /app

USER nodejs

EXPOSE 3000

# 关键修正点：使用 npm start 启动
CMD ["npm", "run", "start"]