# Multi-stage build for smaller, more secure image
# Stage 1: Build
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 first (better layer caching)
COPY Cargo.toml Cargo.lock ./

# Create dummy main.rs to cache dependencies
RUN mkdir src && \
    echo "fn main() {}" > src/main.rs && \
    cargo build --release && \
    rm -rf src

# Copy actual source
COPY src ./src

# Build application
RUN cargo build --release

# Stage 2: Runtime
FROM debian:bookworm-slim

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

# Create non-root user
RUN useradd -m -u 1000 normogen && \
    mkdir -p /app && \
    chown -R normogen:normogen /app

WORKDIR /app

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

# Set permissions
RUN chmod +x /app/normogen-backend && \
    chown normogen:normogen /app/normogen-backend

# Switch to non-root user
USER normogen

# Expose port
EXPOSE 8000

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

# Run with proper signal handling
ENTRYPOINT ["/app/normogen-backend"]
CMD []
