# GChain Production Dockerfile
# Multi-stage build for smaller image size

# Stage 1: Build React client
FROM node:20-alpine AS client-build

WORKDIR /app/client

# Copy client package files
COPY client/package*.json ./

# Install client dependencies
RUN npm ci --only=production

# Copy client source
COPY client/ ./

# Build React app
RUN npm run build

# Stage 2: Build server
FROM node:20-alpine AS server-build

WORKDIR /app

# Copy server package files
COPY package*.json ./

# Install production dependencies only
RUN npm ci --only=production

# Stage 3: Production image
FROM node:20-alpine AS production

WORKDIR /app

# Install dumb-init for proper signal handling
RUN apk add --no-cache dumb-init

# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
    adduser -S nodejs -u 1001

# Copy built server dependencies
COPY --from=server-build /app/node_modules ./node_modules
COPY --from=server-build /app/package*.json ./

# Copy server source
COPY server.js ./
COPY server/ ./server/

# Copy built client
COPY --from=client-build /app/client/build ./client/build

# Create uploads directory with proper permissions
RUN mkdir -p uploads/s2p && chown -R nodejs:nodejs uploads

# Set ownership
RUN chown -R nodejs:nodejs /app

# Switch to non-root user
USER nodejs

# Expose port
EXPOSE 5000

# Environment variables
ENV NODE_ENV=production
ENV PORT=5000

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

# Use dumb-init to handle signals properly
ENTRYPOINT ["dumb-init", "--"]

# Start server
CMD ["node", "server.js"]
