# Multi-stage build for smaller production image
# Stage 1: Build
FROM node:20-alpine AS builder

# Install OpenSSL for Prisma generation
RUN apk add --no-cache openssl

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies (including dev dependencies for build)
RUN npm ci

# Copy source code
COPY . .

# Generate Prisma Client
RUN npx prisma generate

# Build TypeScript
RUN npm run build

# Stage 2: Production
FROM node:20-alpine AS production

# Add metadata
LABEL maintainer="Press.Zone"
LABEL description="Translation API backend for translate.press.zone"

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


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

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./

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

# Copy built application from builder stage
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
COPY --from=builder /app/prisma ./prisma
COPY healthcheck.cjs ./healthcheck.cjs

# Copy scripts if needed for migrations
# COPY scripts ./scripts

# Change ownership to nodejs user
RUN chown -R 1001:1001 /app

# Switch to non-root user
USER 1001:1001

# Expose port
EXPOSE 3000

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
    CMD ["node", "healthcheck.cjs", "api"]

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

# Start the application
CMD ["npm", "start"]
