# Stage 1: Build the application in a build environment
# We use cargo-chef to cache dependencies and speed up future builds
FROM rust:1.78-slim AS chef
WORKDIR /app
RUN cargo install cargo-chef

FROM chef AS planner
COPY . .
# Compute a lock file for dependencies
RUN cargo chef prepare --recipe-path recipe.json

FROM chef AS builder
COPY --from=planner /app/recipe.json recipe.json
# Build dependencies first, this layer will be cached if dependencies don't change
RUN cargo chef cook --release --recipe-path recipe.json
# Copy application code and build the application
COPY . .
RUN cargo build --release --bin data-persistence-service

# Stage 2: Create the final, minimal production image
FROM debian:bookworm-slim AS runtime
WORKDIR /app
# Copy the compiled binary from the builder stage
COPY --from=builder /app/target/release/data-persistence-service /usr/local/bin/
# Copy migrations for `sqlx-cli` if needed at runtime
COPY ./migrations ./migrations
# Expose the port the application will listen on
EXPOSE 8080
# Set the entrypoint for the container
ENTRYPOINT ["/usr/local/bin/data-persistence-service"]
