# Synor Block Explorer Dockerfile
# Multi-stage build for backend API and frontend

# =============================================================================
# Stage 1: Build Rust Backend
# =============================================================================
FROM rust:1.85-bookworm AS backend-builder

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

WORKDIR /app

# Copy manifests
COPY Cargo.toml Cargo.lock ./
COPY src/ src/
COPY crates/ crates/
COPY apps/ apps/

# Build explorer backend
RUN cargo build --release -p synor-explorer

# =============================================================================
# Stage 2: Build Frontend
# =============================================================================
FROM node:20-alpine AS frontend-builder

WORKDIR /app

# Copy frontend source
COPY apps/explorer-web/package*.json ./
RUN npm ci

COPY apps/explorer-web/ ./
RUN npm run build

# =============================================================================
# Stage 3: Runtime Environment
# =============================================================================
FROM debian:bookworm-slim AS runtime

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

# Create non-root user
RUN useradd --create-home --shell /bin/bash explorer

# Copy backend binary
COPY --from=backend-builder /app/target/release/synor-explorer /usr/local/bin/synor-explorer

# Copy frontend build
COPY --from=frontend-builder /app/dist /var/www/explorer

# Set ownership
RUN chown -R explorer:explorer /var/www/explorer

USER explorer
WORKDIR /home/explorer

# Expose ports
EXPOSE 3000

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

# Environment variables
ENV SYNOR_RPC_URL=http://localhost:17110
ENV SYNOR_WS_URL=ws://localhost:17111
ENV EXPLORER_LISTEN_ADDR=0.0.0.0:3000
ENV EXPLORER_STATIC_DIR=/var/www/explorer
ENV RUST_LOG=info

# Default command
ENTRYPOINT ["synor-explorer"]
