# Multi-stage build for Control-Center
# Builds from platform workspace root

# Build stage - Using nightly for edition2024 support (required by async-graphql 7.x)
FROM rustlang/rust:nightly-bookworm AS builder

WORKDIR /workspace

# Install build dependencies
RUN apt-get update && apt-get install -y \
    pkg-config \
    libssl-dev \
    && rm -rf /var/lib/apt/lists/*

# Copy entire platform workspace (required for workspace dependencies)
COPY Cargo.toml Cargo.lock ./
COPY orchestrator ./orchestrator
COPY control-center ./control-center
COPY control-center-ui ./control-center-ui
COPY mcp-server ./mcp-server
COPY installer ./installer

# Build control-center (workspace-aware)
WORKDIR /workspace
RUN cargo build --release --package control-center

# Runtime stage
FROM debian:bookworm-slim

# Install runtime dependencies
RUN apt-get update && apt-get install -y \
    ca-certificates \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user
RUN useradd -m -u 1000 provisioning && \
    mkdir -p /data /var/log/control-center && \
    chown -R provisioning:provisioning /data /var/log/control-center

# Copy binary from builder
COPY --from=builder /workspace/target/release/control-center /usr/local/bin/control-center
RUN chmod +x /usr/local/bin/control-center

# Copy default configuration
COPY control-center/config.defaults.toml /etc/provisioning/config.defaults.toml

# Switch to non-root user
USER provisioning
WORKDIR /app

# Expose port
EXPOSE 8081

# Set environment variables
ENV RUST_LOG=info
ENV DATA_DIR=/data
ENV CONTROL_CENTER_DATABASE_URL=rocksdb:///data/control-center.db

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
    CMD curl -f http://localhost:8081/health || exit 1

# Run the binary with config path
CMD ["control-center", "--config", "/etc/provisioning/config.defaults.toml"]
