FROM node:20-alpine AS builder
WORKDIR /app

# Build shared @genex/common package
COPY packages/common/package*.json ./packages/common/
RUN cd packages/common && npm install
COPY packages/common/ ./packages/common/
RUN cd packages/common && npm run build

# Install service dependencies
COPY services/ai-service/package*.json ./services/ai-service/
WORKDIR /app/services/ai-service
RUN npm install

# Copy common package into node_modules for runtime resolution
RUN mkdir -p node_modules/@genex/common && \
    cp -r /app/packages/common/dist node_modules/@genex/common/ && \
    cp /app/packages/common/package.json node_modules/@genex/common/

# Copy service source and build
COPY services/ai-service/ ./
RUN npm run build

FROM node:20-alpine
WORKDIR /app
RUN apk add --no-cache dumb-init
COPY --from=builder /app/services/ai-service/dist ./dist
COPY --from=builder /app/services/ai-service/node_modules ./node_modules
COPY --from=builder /app/services/ai-service/package.json ./
USER node
EXPOSE 3006
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:3006/api/v1/health || exit 1
CMD ["dumb-init", "node", "dist/main"]
