# 多阶段构建：student-portal 生产镜像（ai14，P6 硬化）
# 用法：docker build -t edu/student-portal:latest -f apps/student-portal/Dockerfile .
# 端口：4001（004 §1.2 强制 4 端 4000-4003）

# ============ Stage 1: 构建 ============
FROM node:22-alpine AS builder
WORKDIR /app

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

# 构建参数：控制 MSW mock 是否启用（生产构建默认 disabled）
# --build-arg NEXT_PUBLIC_API_MOCKING=disabled
ARG NEXT_PUBLIC_API_MOCKING=disabled
ENV NEXT_PUBLIC_API_MOCKING=${NEXT_PUBLIC_API_MOCKING}
# MF 默认关闭（独立壳模式）
ARG NEXT_PUBLIC_MF_ENABLED=false
ENV NEXT_PUBLIC_MF_ENABLED=${NEXT_PUBLIC_MF_ENABLED}
# GraphQL 端点
ARG NEXT_PUBLIC_GRAPHQL_ENDPOINT=/api/v1/student/graphql
ENV NEXT_PUBLIC_GRAPHQL_ENDPOINT=${NEXT_PUBLIC_GRAPHQL_ENDPOINT}

# 拷贝整个 workspace 配置 + 源码（pnpm workspace 需要所有包的 package.json + 源码）
COPY package.json pnpm-lock.yaml* pnpm-workspace.yaml* ./
COPY tsconfig.base.json ./
COPY apps/student-portal ./apps/student-portal
# 拷贝 workspace 共享包（student-portal 的 transpilePackages 依赖）
COPY packages/contracts ./packages/contracts
COPY packages/hooks ./packages/hooks
COPY packages/ui-components ./packages/ui-components
COPY packages/ui-tokens ./packages/ui-tokens
COPY packages/shared-ts ./packages/shared-ts

# 安装依赖（含 devDependencies，构建需要）
RUN pnpm install --filter @edu/student-portal... --frozen-lockfile || pnpm install --filter @edu/student-portal...

# 构建生产产物（禁用 telemetry）
ENV NEXT_TELEMETRY_DISABLED=1
RUN pnpm --filter @edu/student-portal run build

# ============ Stage 2: 运行时 ============
FROM node:22-alpine AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=4001

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

# 拷构建产物 + node_modules（保留 workspace 目录结构以保持 pnpm 符号链接）
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/apps/student-portal/package.json ./apps/student-portal/package.json
COPY --from=builder /app/apps/student-portal/.next ./apps/student-portal/.next
COPY --from=builder /app/apps/student-portal/node_modules ./apps/student-portal/node_modules
COPY --from=builder /app/apps/student-portal/next.config.js ./apps/student-portal/next.config.js

WORKDIR /app/apps/student-portal

USER nextjs
EXPOSE 4001

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

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