name: publish-winrt
on:
  release:
    types: [published]

  workflow_dispatch:
    inputs:
      publish:
        description: 'Publish package (y/n)'
        default: 'n'
      package_version:
        description: 'Package version (major.minor.patch)'
        default: '1.0.0'

jobs:
  build:
    runs-on: windows-latest
    strategy:
      matrix:
        target: [Win32, x64, ARM64]

    steps:
    - uses: actions/checkout@v4

    - name: Create build environment
      shell: cmd
      run: |
        cmake -E make_directory ${{runner.workspace}}/build
        cmake -E copy_directory ${{github.workspace}}/wrappers/winrt/UAP ${{runner.workspace}}/build/dist/UAP
        cmake -E copy_directory ${{github.workspace}}/wrappers/winrt/nuget ${{runner.workspace}}/build/dist/nuget

    - name: Configure CMake
      shell: cmd
      working-directory: ${{runner.workspace}}/build
      run: cmake ${{github.workspace}}/wrappers/winrt -A ${{matrix.target}} -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 -DCMAKE_BUILD_TYPE=Release -DBUILD_WINRT_LIB=ON -DZXING_EXAMPLES=OFF -DZXING_BLACKBOX_TESTS=OFF -DEXTENSION_SDK_OUTPUT=dist/UAP/v0.8.0.0/ExtensionSDKs/ZXingWinRT/1.0.0.0

    - name: Build
      shell: cmd
      working-directory: ${{runner.workspace}}/build
      run: cmake --build . -j8 --config Release

    - uses: actions/upload-artifact@v4
      with:
        name: winrt-${{matrix.target}}-artifacts
        path: ${{runner.workspace}}/build/dist

  publish-package:
    needs: build
    runs-on: windows-latest
    if: ${{ github.event_name == 'release' || github.event.inputs.publish == 'y' }}
    steps:
    - uses: actions/download-artifact@v4
      with:
        name: winrt-Win32-artifacts
    - uses: actions/download-artifact@v4
      with:
        name: winrt-x64-artifacts
    - uses: actions/download-artifact@v4
      with:
        name: winrt-ARM64-artifacts

    - name: Create NuGet package
      if: ${{ github.event_name != 'release' }}
      shell: cmd
      run: nuget pack -Version ${{ github.event.inputs.package_version }} -OutputFileNamesWithoutVersion nuget/ZXingWinRT.nuspec

    - name: Create NuGet package
      if: ${{ github.event_name == 'release' }}
      shell: bash
      env:
          RELEASE_TAG_NAME: ${{ github.event.release.tag_name }}
      run: nuget pack -Version ${RELEASE_TAG_NAME:1} -OutputFileNamesWithoutVersion nuget/ZXingWinRT.nuspec

    - name: Publish NuGet package
      shell: cmd
      run: nuget push huycn.zxingcpp.winrt.nupkg -ApiKey ${{ secrets.NUGET_API_KEY }} -Source https://api.nuget.org/v3/index.json

    - uses: actions/upload-artifact@v4
      with:
        name: nuget-package
        path: huycn.zxingcpp.winrt.nupkg

