# Multi-stage build for kez-chat-server + bundled Svelte SPA.
#
# Stage 1: build the Svelte SPA → web/dist/
# Stage 2: build the Rust binary against kez-core (path dep)
# Stage 3: minimal runtime image with binary + SPA
#
# Build context = repo root (so we can see kez-chat/web/ and rust/).
# docker-compose.yml sets `context: ../..` accordingly.

# ─── Stage 1: build the SPA ────────────────────────────────────────────────
FROM node:22-slim AS webbuild
WORKDIR /src/web
COPY kez-chat/web/package.json kez-chat/web/package-lock.json* ./
RUN npm install --no-audit --no-fund
COPY kez-chat/web/ ./
RUN npm run build

# ─── Stage 2: build the Rust binary ────────────────────────────────────────
FROM rust:1.86-slim AS build
RUN apt-get update && apt-get install -y --no-install-recommends \
        pkg-config libssl-dev ca-certificates \
    && rm -rf /var/lib/apt/lists/*
WORKDIR /src
COPY rust/ /src/rust/
COPY kez-chat/ /src/kez-chat/
WORKDIR /src/kez-chat
RUN cargo build --release --bin kez-chat-server

# ─── Stage 3: runtime ──────────────────────────────────────────────────────
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
        ca-certificates \
    && rm -rf /var/lib/apt/lists/* \
    && useradd -r -u 10001 -m kez

# Rust binary
COPY --from=build /src/kez-chat/target/release/kez-chat-server /usr/local/bin/kez-chat-server
# SPA static files
COPY --from=webbuild /src/web/dist/ /app/web/

USER kez
WORKDIR /data

ENV KEZ_CHAT_BIND=0.0.0.0:6969 \
    KEZ_CHAT_DB=/data/kez-chat.db \
    KEZ_CHAT_SERVER=kez.lat \
    KEZ_CHAT_SIG_SERVER_URL=http://sig-server:7878 \
    KEZ_CHAT_WEB_DIR=/app/web \
    RUST_LOG=info

EXPOSE 6969
ENTRYPOINT ["/usr/local/bin/kez-chat-server"]

# ─── Stage 4 (optional): artifact-only export ──────────────────────────────
# Used by deploy-fast: build this locally on a fast machine for
# --platform=linux/amd64, then `--output type=local,dest=./tmp`
# writes ONLY the two artifacts we ship to the remote — no debian
# rootfs, no rust toolchain, no node_modules.
#
#   docker buildx build \
#     --platform=linux/amd64 \
#     --file kez-chat/deploy/Dockerfile \
#     --target=export \
#     --output type=local,dest=./out \
#     .
#
# Produces: ./out/kez-chat-server, ./out/web/...
FROM scratch AS export
COPY --from=build /src/kez-chat/target/release/kez-chat-server /kez-chat-server
COPY --from=webbuild /src/web/dist/ /web/
