FROM eclipse-temurin:17-jdk-alpine AS builder

WORKDIR /app

# 复制Maven相关文件
COPY pom.xml .
COPY ../../pom.xml ../../

# 复制common模块
COPY ../../common/common-core common/common-core
COPY ../../common/common-web common/common-web

# 复制服务模块
COPY pom.xml .
COPY src src

# 设置Maven镜像加速
RUN mkdir -p /root/.m2 && \
    echo '<?xml version="1.0" encoding="UTF-8"?>' > /root/.m2/settings.xml && \
    echo '<settings>' >> /root/.m2/settings.xml && \
    echo '  <mirrors>' >> /root/.m2/settings.xml && \
    echo '    <mirror>' >> /root/.m2/settings.xml && \
    echo '      <id>aliyun</id>' >> /root/.m2/settings.xml && \
    echo '      <mirrorOf>central</mirrorOf>' >> /root/.m2/settings.xml && \
    echo '      <url>https://maven.aliyun.com/repository/public</url>' >> /root/.m2/settings.xml && \
    echo '    </mirror>' >> /root/.m2/settings.xml && \
    echo '  </mirrors>' >> /root/.m2/settings.xml && \
    echo '</settings>' >> /root/.m2/settings.xml

# 设置pom.xml父项目路径
RUN sed -i 's|<relativePath>../../pom.xml</relativePath>|<relativePath>../pom.xml</relativePath>|g' pom.xml

# 构建
RUN mvn clean package -DskipTests -e

# 运行阶段
FROM eclipse-temurin:17-jre-alpine

WORKDIR /app

# 创建日志目录
RUN mkdir -p /var/log/product-service

# 从构建阶段复制jar包
COPY --from=builder /app/services/product-service/target/*.jar app.jar

# 复制生产环境配置
COPY src/main/resources/deployment/application-prod.yml /app/config/application-prod.yml

# 环境变量配置
ENV JAVA_OPTS="-Xms512m -Xmx1024m -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError -Duser.timezone=Asia/Shanghai"
ENV SPRING_PROFILES_ACTIVE=prod
ENV CONFIG_PATH=/app/config

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:8083/product/api/goods/health || exit 1

# 暴露端口
EXPOSE 8083

# 启动命令
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar app.jar --spring.config.additional-location=file:${CONFIG_PATH}/application-prod.yml"]
