# Multi-stage Dockerfile for Normogen Backend
# Stage 1: Build the Rust application
FROM rust:1.93-slim as builder

WORKDIR /app

# Install build dependencies
RUN apt-get update && apt-get install -y \
    pkg-config \
    libssl-dev \
    && rm -rf /var/lib/apt/lists/*

# Copy manifests
COPY Cargo.toml Cargo.lock ./
COPY src ./src

# Build the application in release mode
RUN cargo build --release

# Stage 2: Runtime image
FROM debian:bookworm-slim

# Install runtime dependencies only
RUN apt-get update && apt-get install -y \
    ca-certificates \
    libssl3 \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

# Create a non-root user
RUN useradd -m -u 1000 normogen

WORKDIR /app

# Copy the binary from builder
COPY --from=builder /app/target/release/normogen-backend /app/normogen-backend

# Change ownership
RUN chown -R normogen:normogen /app

# Switch to non-root user
USER normogen

# Expose the port
EXPOSE 8000

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

# Set the entrypoint to ensure proper signal handling
ENTRYPOINT ["/app/normogen-backend"]

# Run with proper signal forwarding
CMD []
