# Stage 1: Builder - Always uses the latest stable Rust version
FROM rust:latest AS builder

WORKDIR /app

# Install build dependencies
RUN apt-get update && apt-get install -y cmake pkg-config libssl-dev

# 1. Cache dependencies (standard Rust optimization)
COPY Cargo.toml Cargo.lock ./
RUN mkdir src && echo "fn main() {}" > src/main.rs
RUN cargo build --release
RUN rm -rf src

# 2. Build the actual application
COPY src ./src
# Ensure the compiler sees the new source files
RUN touch src/main.rs 
RUN cargo build --release

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

# Install runtime libraries (SSL is required for Postgres/SQLx)
RUN apt-get update && apt-get install -y libssl3 ca-certificates && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy the binary from builder
# Note: if your Cargo.toml 'name' is different, change 'frangipane' to your binary name
COPY --from=builder /app/target/release/frangipane /usr/local/bin/frangipane

# Create storage for avatars
RUN mkdir -p /var/lib/frangipane/avatars

# Default environment
ENV RUST_LOG="info"

# Expose Axum port
EXPOSE 8080

# Command to run. 'db' matches the service name in docker-compose.yml
CMD ["frangipane", "--database", "db:5432", "--port", "8080", "--data-dir", "/var/lib/frangipane"]
