name: Build & Release JAR

on:
  push:
    branches: [main]
  workflow_dispatch:

permissions:
  contents: write

jobs:
  build-release:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: Emulator

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Set up JDK 21
        uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: '21'
          cache: maven

      - name: Bump patch version
        id: bump
        run: |
          CURRENT=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout)
          echo "Current version: $CURRENT"
          IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT"
          NEW="$MAJOR.$MINOR.$((PATCH + 1))"
          echo "New version: $NEW"
          mvn -B versions:set -DnewVersion="$NEW" -DgenerateBackupPoms=false
          echo "new_version=$NEW" >> "$GITHUB_OUTPUT"

      - name: Build JAR
        run: mvn -B clean package -DskipTests

      - name: Commit bumped pom.xml
        run: |
          git config user.name  "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git add pom.xml
          git commit -m "🆙 Bump version to ${{ steps.bump.outputs.new_version }} [skip ci]"
          git push origin HEAD:main

      - name: Generate release notes from latest commit
        working-directory: ${{ github.workspace }}
        env:
          NEW_TAG: v${{ steps.bump.outputs.new_version }}
          TRIGGER_SHA: ${{ github.sha }}
        run: |
          PREV_TAG=$(git tag --sort=-creatordate | head -n1 || true)
          {
            echo "## What's Changed"
            echo ""
            git log -1 --pretty=format:"### %s%n%n%b" "$TRIGGER_SHA"
            echo ""
            echo ""
            if [ -n "$PREV_TAG" ]; then
              echo "**Full Changelog**: https://github.com/${{ github.repository }}/compare/${PREV_TAG}...${NEW_TAG}"
            fi
          } > release_notes.md
          cat release_notes.md

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: v${{ steps.bump.outputs.new_version }}
          name: Release v${{ steps.bump.outputs.new_version }}
          body_path: release_notes.md
          files: Emulator/target/Habbo-${{ steps.bump.outputs.new_version }}-jar-with-dependencies.jar
