# =============================================================================
# Mining Service - Dockerfile
# =============================================================================

# 阶段1: 构建
FROM node:20-alpine AS builder
WORKDIR /app

COPY package*.json ./
COPY tsconfig*.json ./
COPY prisma ./prisma/

RUN npm ci
RUN DATABASE_URL="postgresql://user:pass@localhost:5432/db" npx prisma generate

COPY src ./src
RUN npm run build

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

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

RUN apk add --no-cache curl tzdata openssl

RUN mkdir -p /app && chown nestjs:nodejs /app
WORKDIR /app

USER nestjs

COPY --chown=nestjs:nodejs package*.json ./
RUN npm ci --only=production && npm cache clean --force

COPY --chown=nestjs:nodejs prisma ./prisma/
RUN DATABASE_URL="postgresql://user:pass@localhost:5432/db" npx prisma generate

COPY --chown=nestjs:nodejs --from=builder /app/dist ./dist

RUN printf '#!/bin/sh\nset -e\necho "Running database migrations..."\nnpx prisma migrate deploy\necho "Starting application..."\nexec node dist/main.js\n' > /app/start.sh && chmod +x /app/start.sh

ENV NODE_ENV=production
ENV TZ=Asia/Shanghai

EXPOSE 3021

HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
    CMD curl -f http://localhost:3021/health || exit 1

CMD ["/app/start.sh"]
