name: Release

on:
  push:
    branches:
      - main

env:
  FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true

jobs:
  release:
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Read version from package.json
        id: version
        run: |
          VERSION=$(jq -r '.version' package.json)
          echo "value=$VERSION" >> $GITHUB_OUTPUT
          echo "tag=v$VERSION" >> $GITHUB_OUTPUT

      - name: Check if tag already exists
        id: tag_check
        run: |
          if git ls-remote --tags origin "refs/tags/v${{ steps.version.outputs.value }}" | grep -q .; then
            echo "exists=true" >> $GITHUB_OUTPUT
          else
            echo "exists=false" >> $GITHUB_OUTPUT
          fi

      - name: Extract changelog for this version
        if: steps.tag_check.outputs.exists == 'false'
        id: changelog
        run: |
          VERSION="${{ steps.version.outputs.value }}"
          # Extrai o bloco entre ## [X.Y.Z] e o próximo ## [
          NOTES=$(awk "/^## \[$VERSION\]/{found=1; next} found && /^## \[/{exit} found{print}" CHANGELOG.md)
          # Remove linhas em branco do início e fim
          NOTES=$(echo "$NOTES" | sed '/./,$!d' | sed -e :a -e '/^\n*$/{$d;N;ba}')
          {
            echo "notes<<EOF"
            echo "$NOTES"
            echo "EOF"
          } >> $GITHUB_OUTPUT

      - name: Create tag and GitHub Release
        if: steps.tag_check.outputs.exists == 'false'
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ steps.version.outputs.tag }}
          name: ${{ steps.version.outputs.tag }}
          body: ${{ steps.changelog.outputs.notes }}
          draft: false
          prerelease: false
