# Multi-stage Dockerfile for rust-fafb-q
# Supports both running the server and running tests/benchmarks in isolation.
#
# Stages:
#   builder  — compiles everything (release binary + test/bench binaries)
#   runtime  — minimal image for running the server
#   test     — image with test and bench binaries for isolated test runs

# ── Builder ──────────────────────────────────────────────────────────────────
FROM rust:1.88-bookworm AS builder

WORKDIR /build

# Cache dependency compilation: copy manifests first, build a dummy, then copy
# real source and rebuild.
COPY Cargo.toml Cargo.lock ./
RUN mkdir src && echo 'fn main() {}' > src/main.rs && echo '' > src/lib.rs \
    && cargo build --release 2>/dev/null || true \
    && rm -rf src

COPY . .

# Build release binary
RUN cargo build --release

# Build tests (produces binaries under target/release/deps)
RUN cargo test --release --no-run 2>&1 | tee /tmp/test-build.log

# Build benchmarks
RUN cargo bench --no-run 2>&1 | tee /tmp/bench-build.log

# ── Runtime ──────────────────────────────────────────────────────────────────
FROM debian:bookworm-slim AS runtime

RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY --from=builder /build/target/release/fafb-q /app/fafb-q
COPY config/config.example.toml /app/config/config.toml

# Override bind addresses to 0.0.0.0 so the container is reachable
ENV FAFB_TCP_ADDRESS=0.0.0.0
ENV FAFB_HTTP_ADDRESS=0.0.0.0

EXPOSE 9876 8080

ENTRYPOINT ["/app/fafb-q"]
CMD ["--config", "/app/config/config.toml"]

# ── Test / Bench ─────────────────────────────────────────────────────────────
FROM debian:bookworm-slim AS test

RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy the full build tree so `cargo test` artifacts and fixtures are available
COPY --from=builder /build/target /app/target
COPY --from=builder /build/Cargo.toml /build/Cargo.lock /app/
COPY --from=builder /build/src /app/src
COPY --from=builder /build/tests /app/tests
COPY --from=builder /build/benches /app/benches
COPY --from=builder /build/config /app/config

# Install Rust toolchain in test image (needed for `cargo test` / `cargo bench`)
COPY --from=builder /usr/local/cargo /usr/local/cargo
COPY --from=builder /usr/local/rustup /usr/local/rustup
ENV PATH="/usr/local/cargo/bin:${PATH}"
ENV RUSTUP_HOME="/usr/local/rustup"
ENV CARGO_HOME="/usr/local/cargo"

# Default: run all tests
ENTRYPOINT ["cargo"]
CMD ["test", "--release", "--", "--nocapture"]
