name: Release Workflow

on:
  workflow_dispatch:
    inputs:
      version:
        description: "Release version (e.g., 1.0.0)"
        required: true
        type: string
  push:
    tags:
      - "*.*.*"
  pull_request:
    types: [closed]

jobs:
  determine-version:
    name: Determine Release Version
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.get-version.outputs.version }}
      should-release: ${{ steps.check-release.outputs.should-release }}
    steps:
      - name: Check if should release
        id: check-release
        run: |
          SHOULD_RELEASE="false"

          # Check workflow dispatch
          if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
            SHOULD_RELEASE="true"
          fi

          # Check tag push
          if [ "${{ github.event_name }}" == "push" ] && [ "${{ github.ref_type }}" == "tag" ]; then
            SHOULD_RELEASE="true"
          fi

          # Check PR with [release-*] in title
          if [ "${{ github.event_name }}" == "pull_request" ] && [ "${{ github.event.pull_request.merged }}" == "true" ]; then
            PR_TITLE="${{ github.event.pull_request.title }}"
            if [[ "$PR_TITLE" =~ \[release-[0-9]+\.[0-9]+\.[0-9]+\] ]]; then
              SHOULD_RELEASE="true"
            fi
          fi

          echo "should-release=$SHOULD_RELEASE" >> $GITHUB_OUTPUT

      - name: Get version
        id: get-version
        if: steps.check-release.outputs.should-release == 'true'
        run: |
          VERSION=""

          # Workflow dispatch - use input
          if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
            VERSION="${{ github.event.inputs.version }}"
          fi

          # Tag push - extract from tag
          if [ "${{ github.event_name }}" == "push" ] && [ "${{ github.ref_type }}" == "tag" ]; then
            VERSION="${{ github.ref_name }}"
          fi

          # PR - extract from title
          if [ "${{ github.event_name }}" == "pull_request" ]; then
            PR_TITLE="${{ github.event.pull_request.title }}"
            VERSION=$(echo "$PR_TITLE" | grep -oP '\[release-\K[0-9]+\.[0-9]+\.[0-9]+(?=\])')
          fi

          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "Release version: $VERSION"

  build-and-release:
    name: Build and Release
    needs: determine-version
    if: needs.determine-version.outputs.should-release == 'true'
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

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

      - name: Update version in pom.xml
        run: |
          VERSION="${{ needs.determine-version.outputs.version }}"
          mvn versions:set -DnewVersion=$VERSION
          mvn versions:commit

      - name: Build with Maven
        run: mvn clean package -DskipTests

      - name: Create distribution archive
        run: |
          VERSION="${{ needs.determine-version.outputs.version }}"
          mkdir -p release/schulungsstatistiktool-$VERSION
          cp target/schulungsstatistiktool-$VERSION.jar release/schulungsstatistiktool-$VERSION/
          cp -r target/lib release/schulungsstatistiktool-$VERSION/
          cd release
          zip -r schulungsstatistiktool-$VERSION.zip schulungsstatistiktool-$VERSION
          tar -czf schulungsstatistiktool-$VERSION.tar.gz schulungsstatistiktool-$VERSION

      - name: Generate release notes
        id: release-notes
        run: |
          VERSION="${{ needs.determine-version.outputs.version }}"

          # Get the previous tag
          PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")

          # Generate release notes
          echo "# Release $VERSION" > RELEASE_NOTES.md
          echo "" >> RELEASE_NOTES.md
          echo "## What's Changed" >> RELEASE_NOTES.md
          echo "" >> RELEASE_NOTES.md

          if [ -n "$PREV_TAG" ]; then
            git log $PREV_TAG..HEAD --pretty=format:"* %s (%h)" >> RELEASE_NOTES.md
          else
            git log --pretty=format:"* %s (%h)" >> RELEASE_NOTES.md
          fi

          echo "" >> RELEASE_NOTES.md
          echo "" >> RELEASE_NOTES.md
          echo "**Full Changelog**: https://github.com/${{ github.repository }}/compare/$PREV_TAG...$VERSION" >> RELEASE_NOTES.md

          cat RELEASE_NOTES.md

      - name: Create Git tag
        if: github.event_name != 'push'
        run: |
          VERSION="${{ needs.determine-version.outputs.version }}"
          git config user.name "Gitea CI"
          git config user.email "ci@git.theprivateserver
          git tag -a "$VERSION" -m "Release $VERSION"
          git push origin "$VERSION"

      - name: Create GitHub Release
        uses: actions/create-release@v1
        id: create-release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: ${{ needs.determine-version.outputs.version }}
          release_name: Release ${{ needs.determine-version.outputs.version }}
          body_path: RELEASE_NOTES.md
          draft: false
          prerelease: false

      - name: Upload JAR to Release
        uses: actions/upload-release-asset@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          upload_url: ${{ steps.create-release.outputs.upload_url }}
          asset_path: target/schulungsstatistiktool-${{ needs.determine-version.outputs.version }}.jar
          asset_name: schulungsstatistiktool-${{ needs.determine-version.outputs.version }}.jar
          asset_content_type: application/java-archive

      - name: Upload ZIP to Release
        uses: actions/upload-release-asset@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          upload_url: ${{ steps.create-release.outputs.upload_url }}
          asset_path: release/schulungsstatistiktool-${{ needs.determine-version.outputs.version }}.zip
          asset_name: schulungsstatistiktool-${{ needs.determine-version.outputs.version }}.zip
          asset_content_type: application/zip

      - name: Upload TAR.GZ to Release
        uses: actions/upload-release-asset@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          upload_url: ${{ steps.create-release.outputs.upload_url }}
          asset_path: release/schulungsstatistiktool-${{ needs.determine-version.outputs.version }}.tar.gz
          asset_name: schulungsstatistiktool-${{ needs.determine-version.outputs.version }}.tar.gz
          asset_content_type: application/gzip

      - name: Deploy to Generic Registry
        run: |
          VERSION="${{ needs.determine-version.outputs.version }}"

          # Upload JAR
          curl -X PUT \
            -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
            -H "Content-Type: application/java-archive" \
            --data-binary @target/schulungsstatistiktool-$VERSION.jar \
            "https://gitea.com/api/packages/${{ github.repository_owner }}/generic/schulungsstatistiktool/$VERSION/schulungsstatistiktool-$VERSION.jar"

          # Upload ZIP
          curl -X PUT \
            -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
            -H "Content-Type: application/zip" \
            --data-binary @release/schulungsstatistiktool-$VERSION.zip \
            "https://gitea.com/api/packages/${{ github.repository_owner }}/generic/schulungsstatistiktool/$VERSION/schulungsstatistiktool-$VERSION.zip"

          # Upload TAR.GZ
          curl -X PUT \
            -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
            -H "Content-Type: application/gzip" \
            --data-binary @release/schulungsstatistiktool-$VERSION.tar.gz \
            "https://gitea.com/api/packages/${{ github.repository_owner }}/generic/schulungsstatistiktool/$VERSION/schulungsstatistiktool-$VERSION.tar.gz"

      - name: Summary
        run: |
          VERSION="${{ needs.determine-version.outputs.version }}"
          echo "✅ Release $VERSION completed successfully!"
          echo ""
          echo "📦 Artifacts created:"
          echo "  - JAR: schulungsstatistiktool-$VERSION.jar"
          echo "  - ZIP: schulungsstatistiktool-$VERSION.zip"
          echo "  - TAR.GZ: schulungsstatistiktool-$VERSION.tar.gz"
          echo ""
          echo "🚀 Published to:"
          echo "  - GitHub Release"
          echo "  - Generic Registry"
