FROM rust:1.85-bookworm AS builder
WORKDIR /app

COPY Cargo.toml Cargo.lock ./
COPY migrations ./migrations
COPY src ./src
COPY static ./static

RUN cargo build --release

FROM debian:bookworm-slim AS runtime
RUN apt-get update \
    && apt-get install -y --no-install-recommends ca-certificates curl \
    && rm -rf /var/lib/apt/lists/* \
    && useradd --system --uid 10001 --create-home rustpad \
    && mkdir -p /app/static /data \
    && chown -R rustpad:rustpad /app /data

WORKDIR /app
COPY --from=builder /app/target/release/rustpad /usr/local/bin/rustpad
COPY --from=builder /app/static ./static

USER rustpad
ENV APP_HOST=0.0.0.0 \
    APP_PORT=3000 \
    DATABASE_URL=sqlite:///data/rustpad.db?mode=rwc \
    DATABASE_MAX_CONNECTIONS=8 \
    STATIC_DIR=/app/static \
    RUST_LOG=rustpad=info,tower_http=info

EXPOSE 3000
VOLUME ["/data"]
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD curl --fail --silent http://127.0.0.1:3000/health || exit 1

ENTRYPOINT ["rustpad"]
