# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven

# 权限声明，确保 workflow 有权限写 checks 和 security-events
permissions:
  contents: read
  checks: write
  security-events: write

name: Java CI with Maven

on:
  push:
    branches: [ "main" ]
    paths-ignore:
      - 'README.md'
      - 'LICENSE'
      - '.gitignore'
      - '.gitattributes'
      - 'picture'
  pull_request:
    branches: [ "main" ]
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    strategy:
      matrix:
        java-version: ['8', '17', '21']
      fail-fast: false
    
    name: Build with Java ${{ matrix.java-version }}

    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - name: Set up JDK ${{ matrix.java-version }}
        uses: actions/setup-java@v3
        with:
          java-version: ${{ matrix.java-version }}
          distribution: 'temurin'
          cache: 'maven'
      
      # 优化Maven本地仓库缓存策略
      - name: Cache Maven packages
        uses: actions/cache@v3
        with:
          path: ~/.m2
          key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}-${{ matrix.java-version }}
          restore-keys: |
            ${{ runner.os }}-m2-
      
      # 编译和测试：去掉failOnWarning，避免因为警告导致失败
      - name: Build and Test with Maven
        run: |
          mvn -B verify --file pom.xml -Dmaven.test.failure.ignore=false -Dgpg.skip -Dmaven.javadoc.skip=false
        env:
          MAVEN_OPTS: -Xmx4g -XX:MaxMetaspaceSize=1g
          MAVEN_CLI_OPTS: "--batch-mode --errors --fail-at-end --show-version"

      - name: Publish Test Report
        uses: mikepenz/action-junit-report@v4
        if: success() || failure()
        with:
          report_paths: '**/target/surefire-reports/TEST-*.xml'
          detailed_summary: true
          include_passed: true
          fail_on_failure: true

      - name: Run SonarQube Analysis
        if: matrix.java-version == '17' && github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
        continue-on-error: true
        run: |
          if [[ ! -z "${{ secrets.SONAR_TOKEN }}" ]]; then
            mvn sonar:sonar \
              -Dsonar.projectKey=agileboot \
              -Dsonar.organization=${{ secrets.SONAR_ORGANIZATION || 'default' }} \
              -Dsonar.host.url=${{ secrets.SONAR_HOST_URL || 'https://sonarcloud.io' }} \
              -Dsonar.login=${{ secrets.SONAR_TOKEN }} \
              -Dsonar.java.source=${{ matrix.java-version }}
          else
            echo "Skipping SonarQube analysis - SONAR_TOKEN not configured"
          fi
      
      # 上传构建产物，if-no-files-found 改为 warn
      - name: Upload Build Artifacts
        uses: actions/upload-artifact@v4
        with:
          name: agileboot-artifacts-java-${{ matrix.java-version }}
          path: |
            **/target/*.jar
            !**/target/original-*.jar
          retention-days: 5
          if-no-files-found: warn

      # # 只在 Java 17 版本上更新依赖图（权限和token已修复）
      # - name: Update dependency graph
      #   uses: advanced-security/maven-dependency-submission-action@v4
      #   if: matrix.java-version == '17' && success()
      #   with:
      #     token: ${{ secrets.GITHUB_TOKEN }}

      # # 发送构建状态通知
      # - name: Notify Build Status
      #   if: always()
      #   uses: rtCamp/action-slack-notify@v2.2.1
      #   env:
      #     SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK || '' }}
      #     SLACK_CHANNEL: build-notifications
      #     SLACK_COLOR: ${{ job.status }}
      #     SLACK_TITLE: Build Status for Java ${{ matrix.java-version }}
      #     SLACK_MESSAGE: 'Build ${{ job.status }} on Java ${{ matrix.java-version }}'