# ===========================================
# iConsulting User Service Dockerfile
# ===========================================

# 构建阶段
FROM node:20-alpine AS builder

WORKDIR /app

# 安装 pnpm
RUN corepack enable && corepack prepare pnpm@latest --activate

# 复制 workspace 配置
COPY pnpm-workspace.yaml package.json pnpm-lock.yaml ./
COPY packages/shared/package.json ./packages/shared/
COPY packages/services/user-service/package.json ./packages/services/user-service/

# 安装依赖
RUN pnpm install --frozen-lockfile

# 复制源代码
COPY packages/shared ./packages/shared
COPY packages/services/user-service ./packages/services/user-service
COPY tsconfig.base.json ./

# 构建 shared
RUN pnpm --filter @iconsulting/shared build

# 构建服务
RUN pnpm --filter @iconsulting/user-service build

# 运行阶段
FROM node:20-alpine AS runner

WORKDIR /app

# 创建非 root 用户
RUN addgroup --system --gid 1001 nodejs && \
    adduser --system --uid 1001 nestjs

# 复制构建产物和依赖配置
COPY --from=builder /app/packages/services/user-service/dist ./dist
COPY --from=builder /app/packages/services/user-service/package.json ./

# 移除 workspace: 协议依赖并安装生产依赖
# bcrypt 需要原生编译，安装编译工具
RUN apk add --no-cache jq python3 make g++ && \
    jq 'del(.dependencies["@iconsulting/shared"])' package.json > package.tmp.json && \
    mv package.tmp.json package.json && \
    npm install --omit=dev && \
    apk del python3 make g++

# 复制 shared 包的构建产物 (必须在 npm install 之后，否则会被清空)
COPY --from=builder /app/packages/shared/dist ./node_modules/@iconsulting/shared/dist
COPY --from=builder /app/packages/shared/package.json ./node_modules/@iconsulting/shared/

# 设置环境变量
ENV NODE_ENV=production
ENV PORT=3001

# 切换用户
USER nestjs

# 暴露端口
EXPOSE 3001

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:3001/health || exit 1

# 启动服务
CMD ["node", "dist/main.js"]
