name: Build, test and publish

on:
  push:
    branches:
      - main # or your default branch name

jobs:
  call-reusable-build-test:
    uses: ./.github/workflows/dotnet-build-test.yml

  build-test-publish:
    needs: call-reusable-build-test
    runs-on: windows-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Write SNK file
        shell: pwsh
        run: |
          $env:SNK_BASE64 -split ' ' -join "`n" | Out-File -Encoding utf8 ./SharpToken/keypair.snk.base64.txt
          certutil -decode ./SharpToken/keypair.snk.base64.txt ./SharpToken/keypair.snk
        env:
          SNK_BASE64: ${{ secrets.SNK_BASE64 }}

      - name: Setup .NET
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: |
            3.1.x
            6.0.x
            8.0.x

      - name: Calculate Package Version
        id: calculate_version
        run: |
          $GithubRunNumber = $env:GITHUB_RUN_NUMBER
          $Patch = $GithubRunNumber - 33
          $version = "2.0.$Patch"
          echo "Calculated package version: $version; Patch: $Patch; GitHub Run Number: $GithubRunNumber"
          echo "::set-output name=version::$version"

      - name: Restore dependencies
        run: dotnet restore

      - name: Build
        run: dotnet build --configuration Release --no-restore /p:EnableSigning=true

      - name: Test
        run: dotnet test --no-restore --verbosity normal

      - name: Publish NuGet Package
        run: dotnet pack --configuration Release --no-build --output ./output /p:Version=${{ steps.calculate_version.outputs.version }}

      - name: Push NuGet Package
        run: |
          $packagePath = "./output/SharpToken.${{ steps.calculate_version.outputs.version }}.nupkg"
          dotnet nuget push $packagePath --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate

      - name: Create GitHub Release
        id: create_release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GH_PAT }}
        with:
          tag_name: ${{ steps.calculate_version.outputs.version }}
          release_name: Release ${{ steps.calculate_version.outputs.version }}
          body: Release of version ${{ steps.calculate_version.outputs.version }}
          draft: false
          prerelease: false

      - name: Upload NuGet Package as Release Asset
        uses: actions/upload-release-asset@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GH_PAT }}
        with:
          upload_url: ${{ steps.create_release.outputs.upload_url }}
          asset_path: "./output/SharpToken.${{ steps.calculate_version.outputs.version }}.nupkg"
          asset_name: SharpToken.${{ steps.calculate_version.outputs.version }}.nupkg
          asset_content_type: application/zip
