# ===========================================
# iConsulting Knowledge Service Dockerfile
# ===========================================

FROM node:20-alpine AS builder

WORKDIR /app

RUN corepack enable && corepack prepare pnpm@latest --activate

COPY pnpm-workspace.yaml package.json pnpm-lock.yaml ./
COPY packages/shared/package.json ./packages/shared/
COPY packages/services/knowledge-service/package.json ./packages/services/knowledge-service/

RUN pnpm install --frozen-lockfile

COPY packages/shared ./packages/shared
COPY packages/services/knowledge-service ./packages/services/knowledge-service
COPY tsconfig.base.json ./

RUN pnpm --filter @iconsulting/shared build
RUN pnpm --filter @iconsulting/knowledge-service build

FROM node:20-alpine AS runner

WORKDIR /app

RUN addgroup --system --gid 1001 nodejs && \
    adduser --system --uid 1001 nestjs

COPY --from=builder /app/packages/services/knowledge-service/dist ./dist
COPY --from=builder /app/packages/services/knowledge-service/package.json ./

# 复制 shared 包的构建产物
COPY --from=builder /app/packages/shared/dist ./node_modules/@iconsulting/shared/dist
COPY --from=builder /app/packages/shared/package.json ./node_modules/@iconsulting/shared/

# 移除 workspace: 协议依赖并安装生产依赖
RUN apk add --no-cache jq && \
    jq 'del(.dependencies["@iconsulting/shared"])' package.json > package.tmp.json && \
    mv package.tmp.json package.json && \
    npm install --omit=dev --ignore-scripts

ENV NODE_ENV=production
ENV PORT=3003

USER nestjs
EXPOSE 3003

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

CMD ["node", "dist/main.js"]
