# 多段构建 - 第一阶段：构建应用
# pnpm-lock.yaml 为 lockfileVersion 9，需要 pnpm v9（要求 Node >= 18）
FROM node:18-alpine AS builder

WORKDIR /app

# 可选：使用哪种包管理器构建（默认 pnpm；也可传 npm）
ARG PKG_MANAGER=pnpm
# 可选：镜像加速（例如 https://registry.npmmirror.com）
ARG NPM_REGISTRY=

ENV CI=true

# 先复制依赖清单，最大化缓存命中
COPY package.json ./
COPY package-lock.json* pnpm-lock.yaml* yarn.lock* ./

RUN if [ -n "$NPM_REGISTRY" ]; then npm config set registry "$NPM_REGISTRY"; fi

RUN set -eux; \
  if [ "$PKG_MANAGER" = "pnpm" ]; then \
    npm i -g pnpm@9 && pnpm i --frozen-lockfile; \
  elif [ "$PKG_MANAGER" = "npm" ]; then \
    npm ci --no-audit --fund=false; \
  else \
    echo "Unsupported PKG_MANAGER=$PKG_MANAGER (use pnpm or npm)"; \
    exit 1; \
  fi

# 复制源代码
COPY . .

RUN set -eux; \
  if [ "$PKG_MANAGER" = "pnpm" ]; then \
    pnpm run build:prod; \
  else \
    npm run build:prod; \
  fi

# 多段构建 - 第二阶段：Nginx部署
FROM nginx:alpine AS final

# 复制自定义nginx配置
COPY nginx.conf /etc/nginx/nginx.conf

# 从构建阶段复制构建产物
COPY --from=builder /app/dist /usr/share/nginx/html

EXPOSE 80

# 健康检查：使用 nginx.conf 的 /health，避免额外安装 curl
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget -qO- http://127.0.0.1/health >/dev/null || exit 1

CMD ["nginx", "-g", "daemon off;"]
