# 多阶段构建：Next.js 生产镜像（parent-portal MF Remote）
# 用法：docker build -t edu/parent-portal:latest -f apps/parent-portal/Dockerfile .
# 依据：02-architecture-design.md §16 部署、G1 裁决（首次即多阶段）
# 端口：4002（4 端 portal 强制 4000-4003）

# ============ Builder ============
FROM node:20-alpine AS builder
WORKDIR /app

# 启用 pnpm
RUN corepack enable && corepack prepare pnpm@9.12.0 --activate

# 先拷依赖清单，利用缓存
COPY package.json pnpm-lock.yaml* pnpm-workspace.yaml* ./
COPY apps/parent-portal/package.json ./apps/parent-portal/
# 安装依赖（含 devDependencies，构建需要）
RUN pnpm install --filter @edu/parent-portal... --frozen-lockfile || pnpm install --filter @edu/parent-portal...

# 拷源码
COPY apps/parent-portal ./apps/parent-portal

# 构建（禁用 telemetry，生产模式）
ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_ENV=production
RUN pnpm --filter @edu/parent-portal run build

# ============ Runtime ============
FROM node:20-alpine AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=4002

# 非 root 用户运行
RUN addgroup -g 1001 -S nodejs && adduser -S nextjs -u 1001

# 拷构建产物与必要清单
COPY --from=builder /app/apps/parent-portal/package.json ./package.json
COPY --from=builder /app/apps/parent-portal/.next ./.next
COPY --from=builder /app/apps/parent-portal/public ./public
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/apps/parent-portal/next.config.js ./next.config.js

USER nextjs
EXPOSE 4002

# 健康检查
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
  CMD wget --quiet --spider http://localhost:4002/api/health || exit 1

CMD ["node_modules/.bin/next", "start", "-p", "4002"]
