# Stage 1: Build the JAR
FROM maven:3.9-eclipse-temurin-11 AS builder

WORKDIR /build

# Copy pom.xml and protobuf definitions first for better caching
COPY pom.xml .
COPY protobuf ../protobuf/

# Download dependencies (cached if pom.xml doesn't change)
RUN mvn dependency:go-offline

# Copy source code
COPY src ./src

# Build the JAR
RUN mvn clean package -DskipTests

# For dev environment: replace topics.yaml with topics-dev.yaml in the JAR
# This avoids replication factor errors with only 1 Kafka broker
RUN mkdir -p /tmp/jar-overlay && \
    cp /build/src/main/resources/topics-dev.yaml /tmp/jar-overlay/topics.yaml && \
    cd /tmp/jar-overlay && \
    jar uf /build/target/trading-flink-1.0-SNAPSHOT.jar topics.yaml

# Stage 2: Create the Flink runtime image
FROM flink:1.20.0-java11

# Copy the built JAR to the Flink lib directory
COPY --from=builder /build/target/trading-flink-1.0-SNAPSHOT.jar /opt/flink/usrlib/trading-flink.jar

# Copy configuration files
COPY config.example.yaml /opt/flink/conf/app-config.yaml

# Set the entrypoint to use Application mode
# The job will auto-submit on startup
USER flink
