# Release workflow for publishing NuGet packages
name: Release

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      version:
        description: 'Package version (e.g., 1.0.0-preview.5)'
        required: true
        type: string

env:
  DOTNET_VERSION: '9.0.x'
  DOTNET_NOLOGO: true
  DOTNET_CLI_TELEMETRY_OPTOUT: true

jobs:
  release:
    name: Build and Publish
    runs-on: ubuntu-latest

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

    - name: Setup .NET
      uses: actions/setup-dotnet@v4
      with:
        dotnet-version: ${{ env.DOTNET_VERSION }}

    - name: Install Linux dependencies
      run: |
        sudo apt-get update
        sudo apt-get install -y libx11-dev libxrandr-dev libxcursor-dev libxi-dev libgl1-mesa-dev

    - name: Determine version
      id: version
      run: |
        if [ "${{ github.event_name }}" = "release" ]; then
          VERSION="${{ github.event.release.tag_name }}"
          VERSION="${VERSION#v}"  # Remove 'v' prefix if present
        else
          VERSION="${{ inputs.version }}"
        fi
        echo "version=$VERSION" >> $GITHUB_OUTPUT
        echo "Using version: $VERSION"

    - name: Restore dependencies
      run: dotnet restore

    - name: Build
      run: dotnet build --configuration Release --no-restore

    - name: Run tests
      run: dotnet test --configuration Release --no-build --verbosity normal

    - name: Pack NuGet package
      run: dotnet pack --configuration Release --no-build -o ./nupkg /p:PackageVersion=${{ steps.version.outputs.version }}

    - name: Upload NuGet package artifact
      uses: actions/upload-artifact@v6
      with:
        name: nuget-package-${{ steps.version.outputs.version }}
        path: ./nupkg/*.nupkg

    - name: Publish to NuGet.org
      if: github.event_name == 'release'
      run: |
        dotnet nuget push ./nupkg/*.nupkg \
          --api-key ${{ secrets.NUGET_API_KEY }} \
          --source https://api.nuget.org/v3/index.json \
          --skip-duplicate
      env:
        NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }}

    - name: Attach packages to release
      if: github.event_name == 'release'
      uses: softprops/action-gh-release@v2
      with:
        files: ./nupkg/*.nupkg
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
