# Build stage
FROM asdmimages.azurecr.io/base/eclipse-temurin:21-jdk-alpine AS build
WORKDIR /app

# Copy maven wrapper and pom.xml
# Copy parent POM to /pom.xml so child `relativePath=../pom.xml` resolves.
COPY pom.xml /pom.xml

# Copy module wrapper and module pom into /app
COPY asdm-admin-services-core/mvnw .
COPY asdm-admin-services-core/.mvn .mvn
COPY asdm-admin-services-core/pom.xml ./pom.xml

# Create Maven settings with Aliyun mirror
RUN mkdir -p /root/.m2 && \
    echo '<?xml version="1.0" encoding="UTF-8"?>' > /root/.m2/settings.xml && \
    echo '<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"' >> /root/.m2/settings.xml && \
    echo '          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' >> /root/.m2/settings.xml && \
    echo '          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0' >> /root/.m2/settings.xml && \
    echo '          https://maven.apache.org/xsd/settings-1.0.0.xsd">' >> /root/.m2/settings.xml && \
    echo '  <mirrors>' >> /root/.m2/settings.xml && \
    echo '    <mirror>' >> /root/.m2/settings.xml && \
    echo '      <id>aliyunmaven</id>' >> /root/.m2/settings.xml && \
    echo '      <name>阿里云公共仓库</name>' >> /root/.m2/settings.xml && \
    echo '      <url>https://maven.aliyun.com/repository/public</url>' >> /root/.m2/settings.xml && \
    echo '      <mirrorOf>central</mirrorOf>' >> /root/.m2/settings.xml && \
    echo '    </mirror>' >> /root/.m2/settings.xml && \
    echo '    <mirror>' >> /root/.m2/settings.xml && \
    echo '      <id>aliyun-spring</id>' >> /root/.m2/settings.xml && \
    echo '      <name>阿里云Spring仓库</name>' >> /root/.m2/settings.xml && \
    echo '      <url>https://maven.aliyun.com/repository/spring</url>' >> /root/.m2/settings.xml && \
    echo '      <mirrorOf>spring*</mirrorOf>' >> /root/.m2/settings.xml && \
    echo '    </mirror>' >> /root/.m2/settings.xml && \
    echo '  </mirrors>' >> /root/.m2/settings.xml && \
    echo '</settings>' >> /root/.m2/settings.xml

# Download dependencies (cached layer)
RUN ./mvnw dependency:go-offline -B

# Copy source code and build
COPY asdm-admin-services-core/src ./src
RUN ./mvnw clean package -DskipTests -B

# Runtime stage
FROM asdmimages.azurecr.io/base/eclipse-temurin:21-jre-alpine

# Switch to root to create directories and set permissions
USER root
WORKDIR /app

# Create logs directory and ensure app user owns it (NAS volume access compatibility)
RUN mkdir -p /app/logs && \
    chown -R 1000:1000 /app

# Copy the built jar
COPY --from=build /app/target/*.jar app.jar

# Ensure jar is owned by app user
RUN chown 1000:1000 app.jar

# Switch back to non-root user for runtime
USER 1000

# Expose port
EXPOSE 8880

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
  CMD wget -q --spider http://localhost:8880/actuator/health || exit 1

# Run the application
ENTRYPOINT ["java", "-jar", "app.jar"]
