# Generated by GitHub Copilot
#
# Build stage — Java 21 LTS + Maven (used only for local dev via --target local).
# The CI workflow builds the JAR natively on the Pi runner before calling docker build
# to avoid QEMU's unreliable TLS stack causing Maven Central downloads to time out.
FROM eclipse-temurin:21-jdk-alpine AS build
WORKDIR /workspace

# Download Maven via curl — avoids apk's OpenJDK pulling in a conflicting JDK version.
ENV MAVEN_VERSION=3.9.9
RUN apk add --no-cache curl && \
    curl -fsSL https://archive.apache.org/dist/maven/maven-3/${MAVEN_VERSION}/binaries/apache-maven-${MAVEN_VERSION}-bin.tar.gz \
      | tar -xz -C /opt && \
    ln -s /opt/apache-maven-${MAVEN_VERSION} /opt/maven
ENV PATH="/opt/maven/bin:${PATH}"

COPY pom.xml .
# Pre-fetch deps as a cached layer; rebuilds on source-only changes skip this step.
RUN mvn -q -ntp dependency:go-offline || true

COPY src src
RUN mvn -q -ntp clean package -DskipTests

# ── Runtime base — shared between local and ci-image targets ──────────────────
FROM eclipse-temurin:21-jre-alpine AS runtime-base
WORKDIR /app

# Non-root user — principle of least privilege (REQ-SEC-001)
RUN addgroup -S caloriecounter && adduser -S caloriecounter -G caloriecounter
USER caloriecounter

EXPOSE 8080

# Container-aware heap sizing: use 75% of cgroup memory limit
ENV JAVA_OPTS="-XX:+UseContainerSupport -XX:MaxRAMPercentage=75"
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar app.jar"]

# ── local target ──────────────────────────────────────────────────────────────
# Copies JAR from the Maven build stage above.
# Usage: docker build --target local -t calorie-counter-api .
FROM runtime-base AS local
COPY --from=build /workspace/target/*.jar app.jar

# ── ci-image target (DEFAULT) ─────────────────────────────────────────────────
# Copies a pre-built JAR from the Docker build context.
# The CI workflow builds the JAR natively (outside QEMU) before docker build,
# avoiding 20-min Maven downloads through QEMU's unreliable TLS stack.
# Usage: docker build --build-arg JAR_FILE=target/calorie-counter-backend-1.0.0-SNAPSHOT.jar .
FROM runtime-base AS ci-image
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
