# Dockerfile

# ---- Builder Stage ----
    FROM rust:1.78-slim AS builder

    # Install build dependencies (like openssl for native-tls feature of sqlx)
    # Use Debian package names
    RUN apt-get update && apt-get install -y --no-install-recommends \
        pkg-config \
        libssl-dev \
     && rm -rf /var/lib/apt/lists/*
    
    WORKDIR /app
    
    # Copy manifests first to leverage Docker cache for dependencies
    COPY Cargo.toml Cargo.lock ./
    # Dummy src/main.rs to build dependencies only if needed
    RUN mkdir src && echo "fn main(){}" > src/main.rs
    # Build dependencies only (can take time)
    # Use --release for optimized dependencies if desired, but target/debug might be faster for iteration
    # RUN cargo build --release
    RUN cargo build
    
    # Copy the actual source code
    COPY src ./src
    
    # Build the final application binary (optimized for release)
    # Ensure previous build steps are cleaned if needed
    RUN touch src/main.rs && cargo build --release
    
    
    # ---- Runtime Stage ----
    FROM debian:stable-slim AS runtime
    
    # Install runtime dependencies (like ca-certificates and openssl libs)
    RUN apt-get update && apt-get install -y --no-install-recommends \
        ca-certificates \
        libssl3 \
     && rm -rf /var/lib/apt/lists/*
    
    WORKDIR /app
    
    # Copy the compiled binary from the builder stage
    COPY --from=builder /app/target/release/lms-backend /usr/local/bin/lms-backend
    
    # Copy .env file - Alternatively, manage via Docker Compose environment vars
    # COPY .env .env # If you want .env inside the image (less flexible)
    
    # Expose the port the application listens on (from .env or default)
    EXPOSE 8080
    
    # Set the entrypoint to run the application
    # Use environment variables for configuration (DATABASE_URL, SERVER_ADDR) passed via Docker Compose
    CMD ["lms-backend"]