# Build stage
FROM rustlang/rust:nightly-bookworm AS builder

WORKDIR /app

# Copy manifests first for dependency caching
COPY Cargo.toml Cargo.lock ./

# Create dummy src to build dependencies
RUN mkdir src && echo "fn main() {}" > src/main.rs
RUN cargo build --release
RUN rm -rf src

# Copy actual source code
COPY src ./src
COPY migrations ./migrations

# Touch main.rs to invalidate the dummy build
RUN touch src/main.rs

# Build the actual application
RUN cargo build --release

# Runtime stage
FROM debian:bookworm-slim

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

WORKDIR /app

# Copy the binary from builder
COPY --from=builder /app/target/release/nexus /app/nexus

# Copy migrations for runtime (if needed for embedded migrations)
COPY --from=builder /app/migrations ./migrations

# Copy static files (logo for emails, etc.)
COPY static ./static

# Copy entrypoint script
COPY entrypoint.sh /app/entrypoint.sh
RUN chmod 755 /app/entrypoint.sh

# Create non-root user
RUN useradd -r -s /bin/false nexus
USER nexus

EXPOSE 5050

ENV RUST_LOG=nexus=info,tower_http=info

ENTRYPOINT ["/app/entrypoint.sh"]
