# Stage 1: Build
FROM maven:3.9-eclipse-temurin-17-alpine AS builder

WORKDIR /app

# 复制pom.xml和依赖配置
COPY pom.xml .
COPY common/pom.xml common/
COPY services/dashboard-service/pom.xml services/dashboard-service/

# 下载依赖（利用Docker缓存）
RUN mvn dependency:go-offline -B

# 复制源代码
COPY . .

# 构建应用
WORKDIR /app/services/dashboard-service
RUN mvn clean package -DskipTests -B

# Stage 2: Runtime
FROM eclipse-temurin:17-jre-alpine

# 安全：创建非root用户
RUN addgroup -g 1001 -S appgroup && \
    adduser -u 1001 -S appuser -G appgroup

WORKDIR /app

# 创建日志目录
RUN mkdir -p /app/logs && chown -R appuser:appgroup /app

# 从构建阶段复制JAR文件
COPY --from=builder /app/services/dashboard-service/target/*.jar app.jar

# 设置文件权限
RUN chown appuser:appgroup app.jar

# 环境变量配置
ENV JAVA_OPTS="-Xms512m -Xmx1024m -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/app/logs/heapdump.hprof"
ENV SPRING_PROFILES_ACTIVE=prod

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD wget -q --spider http://localhost:8086/actuator/health || exit 1

# 暴露端口
EXPOSE 8086

# 切换到非root用户
USER appuser

# 启动命令
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar app.jar"]
