name: Publish NuGet package
on:
  workflow_dispatch:

jobs:
  prereleaseCheck:
    runs-on: ubuntu-latest
    environment: AsyncAPI 
    name: Check release
    steps:
    - name: Checkout repository
      uses: actions/checkout@v1

    - name: Semantic Release
      uses: cycjimmy/semantic-release-action@v3
      id: semantic
      with:
        extra_plugins: |
          conventional-changelog-conventionalcommits
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

    - name: Get token
      if: steps.semantic.outputs.new_release_published == 'true'
      id: get_token
      uses: peter-murray/workflow-application-token-action@v2.1.0
      with:
        application_id: ${{ secrets.APPLICATION_ID }}
        application_private_key: ${{ secrets.APPLICATION_PRIVATE_KEY }}

    - name: Commit changes
      if: steps.semantic.outputs.new_release_published == 'true'
      env:
        GITHUB_TOKEN: ${{ steps.get_token.outputs.token }}
        FILE_TO_COMMIT: CHANGELOG.md
        DESTINATION_BRANCH: ${{ github.ref }}
      run: |
        export MESSAGE="chore: update $FILE_TO_COMMIT"
        export SHA=$( git rev-parse $DESTINATION_BRANCH:$FILE_TO_COMMIT )
        export CONTENT=$( base64 -i $FILE_TO_COMMIT )
        gh api --method PUT /repos/:owner/:repo/contents/$FILE_TO_COMMIT \
          --field message="$MESSAGE" \
          --field content="$CONTENT" \
          --field encoding="base64" \
          --field branch="$DESTINATION_BRANCH" \
          --field sha="$SHA"

    outputs:
      trigger_release: ${{ steps.semantic.outputs.new_release_published }}
      version: ${{ steps.semantic.outputs.new_release_published == 'true' && steps.semantic.outputs.new_release_version }}

  release:
    runs-on: ubuntu-latest
    name: Publish NuGet packages
    needs: prereleaseCheck
    environment: AsyncAPI 
    strategy:
      matrix:
        package-name: [ "LEGO.AsyncAPI", "LEGO.AsyncAPI.Readers", "LEGO.AsyncAPI.Bindings" ]
    steps:
      - name: Checkout repository
        uses: actions/checkout@v1
        
      - name: Setup .NET Core @ Latest
        if: needs.prereleaseCheck.outputs.trigger_release == 'true'
        uses: actions/setup-dotnet@v1

      - name: Build ${{ matrix.package-name }} project and pack NuGet package
        if: needs.prereleaseCheck.outputs.trigger_release == 'true'
        run: dotnet pack src/${{ matrix.package-name }}/${{ matrix.package-name }}.csproj -c Release -o out-${{ matrix.package-name }} -p:PackageVersion=${{ needs.prereleaseCheck.outputs.version }}

      - name: Push generated package to GitHub Packages registry
        if: needs.prereleaseCheck.outputs.trigger_release == 'true'
        run: dotnet nuget push out-${{ matrix.package-name }}/*.nupkg -s https://api.nuget.org/v3/index.json --skip-duplicate -n --api-key ${{secrets.NUGET}}
