name: Build and Release

on:
  push:
    branches:
      - "rebuild-develop"   # develop 分支只构建
      - "rebuild-release"   # release 分支构建 + 发布
  workflow_dispatch: # 允许手动触发

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Set up JDK 17
        uses: actions/setup-java@v3
        with:
          distribution: temurin
          java-version: 17

      - name: Grant execute permission for Gradlew
        run: chmod +x gradlew

      - name: Build with Gradle
        run: ./gradlew clean build

      - name: Upload common jar
        uses: actions/upload-artifact@v4
        with:
          name: Common
          path: Common/build/libs/*.jar

      - name: Upload common api jar
        uses: actions/upload-artifact@v4
        with:
          name: CommonApi
          path: CommonApi/build/libs/*.jar

  release:
    needs: build
    runs-on: ubuntu-latest
    if: github.ref_name == 'rebuild-release'  # 仅在 release 分支执行 release job
    steps:
      # 下载构建产物
      - name: Download Common artifact
        uses: actions/download-artifact@v4
        with:
          name: Common
          path: ./build-artifacts/Common

      - name: Download CommonApi artifact
        uses: actions/download-artifact@v4
        with:
          name: CommonApi
          path: ./build-artifacts/CommonApi

      # 创建 GitHub Release
      - name: Create GitHub Release
        id: create_release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: "release-${{ github.run_number }}"  # 可用 run_number 或自定义版本号
          name: Release ${{ github.run_number }}
          body: 自动发布所有子项目构建产物
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      # 上传子项目 JAR
      - name: Upload jars to Release
        run: |
          for file in ./build-artifacts/**/*.jar; do
            echo "Uploading $file"
            gh release upload "release-${GITHUB_RUN_NUMBER}" "$file" --repo "${GITHUB_REPOSITORY}" --clobber
          done
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
