# ====== Build stage ======
FROM maven:3.9.9-eclipse-temurin-17 AS build

WORKDIR /app

COPY pom.xml .
RUN mvn -q -e -B dependency:go-offline

COPY src ./src

RUN mvn -q -e -B clean package -DskipTests

# ====== Runtime stage ======
FROM eclipse-temurin:17-jre

WORKDIR /app

# Copy fat jar from build stage
COPY --from=build /app/target/*.jar app.jar

# Copy startup script (optional - only used if secret file doesn't exist)
COPY scripts/create-secret-file.sh /app/create-secret-file.sh
RUN chmod +x /app/create-secret-file.sh

# Copy logback-spring.xml to config directory (can be overridden by volume mount)
COPY src/main/resources/logback-spring.xml /app/config/logback-spring.xml

# Create log directory
RUN mkdir -p /app/logs && chmod 755 /app/logs

# Expose port (for local/docker-compose/documentation)
EXPOSE 8080

# Default environment variables (can be overridden in docker-compose)
ENV JAVA_OPTS=""
ENV LOGGING_CONFIG="/app/config/logback-spring.xml"
ENV LOG_DIR="/app/logs"

# Start app
# If /run/secrets/lottery-config.properties exists (mounted), ConfigLoader will use it
# Otherwise, create-secret-file.sh will create it from env vars (for development/testing)
# Uses external logback-spring.xml for runtime log level changes
# Ensure logback-spring.xml exists and is a file (not a directory)
ENTRYPOINT ["sh", "-c", "if [ ! -f /run/secrets/lottery-config.properties ]; then /app/create-secret-file.sh; fi && if [ ! -f \"${LOGGING_CONFIG}\" ] || [ -d \"${LOGGING_CONFIG}\" ]; then echo 'Warning: ${LOGGING_CONFIG} not found or is a directory, using default from JAR'; LOGGING_CONFIG=''; fi && java $JAVA_OPTS ${LOGGING_CONFIG:+-Dlogging.config=${LOGGING_CONFIG}} -DLOG_DIR=${LOG_DIR} -jar app.jar"]

