name: Release NuGet Packages

on:
  release:
    types: [published]
  workflow_dispatch:

env:
  DOTNET_NOLOGO: true
  DOTNET_CLI_TELEMETRY_OPTOUT: true
  NUGET_SOURCE_URL: https://nuget.sabp.ir/v3/index.json
  PACKAGE_OUTPUT: ./artifacts/nuget
  PACKAGE_PROJECTS: src/SufiChain.SufiBlazor/SufiChain.SufiBlazor.csproj
  # TODO: Uncomment these when demo packages are ready to build and release.
  # PACKAGE_PROJECTS: >-
  #   src/SufiChain.SufiBlazor/SufiChain.SufiBlazor.csproj
  #   src/SufiChain.SufiBlazor.Demo.Localization/SufiChain.SufiBlazor.Demo.Localization.csproj
  #   src/SufiChain.SufiBlazor.Demo/SufiChain.SufiBlazor.Demo.csproj
  RELEASE_TAG: ${{ gitea.event.release.tag_name }}
  REF_NAME: ${{ gitea.ref_name }}
  REPOSITORY: ${{ gitea.repository }}

jobs:
  pack-and-push:
    runs-on: ubuntu-latest
    container:
      image: mcr-mirror.liara.ir/dotnet/sdk:10.0.202

    steps:
      - name: Checkout
        shell: bash
        run: |
          set -euo pipefail
          git clone --depth 1 https://git.sabp.ir/sufi-chain/sufi-blazor.git .
          echo "=== Workspace contents ==="
          ls -la

      - name: Restore selected projects
        shell: bash
        run: |
          set -euo pipefail
          for project in $PACKAGE_PROJECTS; do
            dotnet restore "$project"
          done

      - name: Build selected projects
        shell: bash
        run: |
          set -euo pipefail
          for project in $PACKAGE_PROJECTS; do
            dotnet build "$project" --configuration Release --no-restore
          done

      - name: Pack selected projects
        shell: bash
        run: |
          set -euo pipefail
          mkdir -p "$PACKAGE_OUTPUT"

          if [ -n "${RELEASE_TAG:-}" ]; then
            version="$RELEASE_TAG"
          else
            version="0.0.0-dev.$(date +%Y%m%d%H%M%S)"
          fi
          version="${version#v}"
          echo "=== Packing version: $version ==="

          for project in $PACKAGE_PROJECTS; do
            dotnet pack "$project" \
              --configuration Release \
              --no-build \
              --output "$PACKAGE_OUTPUT" \
              -p:PackageVersion="$version" \
              -p:ContinuousIntegrationBuild=true
          done

      - name: Push packages to BaGet
        shell: bash
        env:
          NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }}
        run: |
          set -euo pipefail
          if [ -z "${NUGET_API_KEY:-}" ]; then
            echo "NUGET_API_KEY secret is required."
            exit 1
          fi

          shopt -s nullglob
          packages=("$PACKAGE_OUTPUT"/*.nupkg)
          if [ ${#packages[@]} -eq 0 ]; then
            echo "No NuGet packages were produced."
            exit 1
          fi

          for package in "${packages[@]}"; do
            dotnet nuget push "$package" \
              --source "$NUGET_SOURCE_URL" \
              --api-key "$NUGET_API_KEY" \
              --skip-duplicate
          done
