name: Preview Release

on:
  push:
    branches:
      - dev

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: 'temurin'
      - run: chmod +x gradlew
      - run: ./gradlew clean build -x test

      # Tag erstellen, bevor Release angelegt wird
      - name: Create Preview Tag
        run: |
          git config user.name "github-actions"
          git config user.email "github-actions@users.noreply.github.com"
          git tag preview-${{ github.run_number }}
          git push origin preview-${{ github.run_number }}

      - name: Create Preview Release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: preview-${{ github.run_number }}
          name: "Preview Build #${{ github.run_number }}"
          prerelease: true
          files: build/libs/*.jar
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Cleanup old Preview Releases
        run: |
          gh release list --limit 100 --repo $GITHUB_REPOSITORY \
          | grep preview \
          | sort -rk2 \
          | awk 'NR>10 {print $1}' \
          | xargs -I {} gh release delete {} --repo $GITHUB_REPOSITORY --yes
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
