ARG SERVICE_MODULE=tenant-service

FROM --platform=linux/amd64 maven:3.9.9-eclipse-temurin-21 AS build
ARG SERVICE_MODULE
WORKDIR /workspace

# Copy only pom files first — layer cached until any pom.xml changes
COPY pom.xml ./pom.xml
COPY maven-settings.xml ./maven-settings.xml
COPY common/pom.xml ./common/pom.xml
COPY im-sdk/pom.xml ./im-sdk/pom.xml
COPY tenant-service/pom.xml ./tenant-service/pom.xml
COPY im-service/pom.xml ./im-service/pom.xml
COPY push-service/pom.xml ./push-service/pom.xml
COPY update-service/pom.xml ./update-service/pom.xml
COPY demo-service/pom.xml ./demo-service/pom.xml
COPY file-service/pom.xml ./file-service/pom.xml
COPY license-service/pom.xml ./license-service/pom.xml

# Pre-download dependencies using BuildKit cache mount — persisted across builds
RUN --mount=type=cache,target=/root/.m2 \
    mvn -s /workspace/maven-settings.xml -pl ${SERVICE_MODULE} -am \
        dependency:go-offline -q

# Copy source — invalidates only the compile layer, not the deps layer
COPY common ./common
COPY im-sdk ./im-sdk
COPY tenant-service ./tenant-service
COPY im-service ./im-service
COPY push-service ./push-service
COPY update-service ./update-service
COPY demo-service ./demo-service
COPY file-service ./file-service
COPY license-service ./license-service

RUN --mount=type=cache,target=/root/.m2 \
    mvn -s /workspace/maven-settings.xml -pl ${SERVICE_MODULE} -am -DskipTests package

# Use Alpine-based JRE — ~100MB smaller than jammy
FROM --platform=linux/amd64 eclipse-temurin:21-jre-alpine
WORKDIR /app
ARG SERVICE_MODULE

COPY --from=build /workspace/${SERVICE_MODULE}/target/${SERVICE_MODULE}-0.1.0-SNAPSHOT.jar /app/app.jar

ENTRYPOINT ["java", "-jar", "/app/app.jar"]
