# syntax=docker/dockerfile:1

# ── Stage 1: Build standalone binary ─────────────────────────────────────────
FROM oven/bun:1 AS builder
WORKDIR /build

# Install dependencies first (cache layer)
COPY package.json ./
RUN bun install

# Copy source and compile
COPY tsconfig.json ./
COPY src/ ./src/
RUN bun build --compile --minify --sourcemap --bytecode \
    --target=bun-linux-x64 \
    ./src/main.ts \
    --outfile ./dist/config-server

# ── Stage 2: Minimal runtime image ───────────────────────────────────────────
FROM debian:bookworm-slim

# Install curl for HEALTHCHECK (binary is ~100MB anyway, curl adds negligible overhead)
RUN apt-get update \
    && apt-get install -y --no-install-recommends curl \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user
RUN groupadd --system --gid 1001 app \
    && useradd --system --uid 1001 --gid app --no-create-home app

WORKDIR /app

# Copy compiled binary
COPY --from=builder --chown=app:app /build/dist/config-server ./config-server

# Prepare data directory (mount a volume here for persistence)
RUN mkdir -p /data && chown app:app /data

USER app

# Default data path — compose will bind-mount host:${containerName}/data here
ENV CONFIG_DB_PATH=/data/config.db
VOLUME ["/data"]
EXPOSE 4000

# Health check against /v1/health; respects CONFIG_PORT if overridden
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
    CMD curl -sf http://localhost:${CONFIG_PORT:-4000}/v1/health

CMD ["./config-server"]
