name: Publish to Microsoft Store

# 构建 MSIX 并发布到微软商店。
# - 首次提交必须手动上传到 Partner Center（参见仓库文档），之后版本才能自动发布。
# - 发布步骤仅在配置了 MSSTORE_PRODUCT_ID 仓库变量时执行；否则只构建 MSIX 作为产物。

on:
  workflow_dispatch:
  push:
    tags:
      - 'v*'

jobs:
  msix:
    runs-on: windows-latest

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: lts/*
          cache: npm

      - name: Install Rust stable
        uses: dtolnay/rust-toolchain@stable

      - name: Rust cache
        uses: swatinem/rust-cache@v2
        with:
          workspaces: './src-tauri -> target'

      - name: Install frontend dependencies
        run: npm ci

      - name: Build MSIX
        shell: pwsh
        env:
          MSSTORE_PACKAGE_IDENTITY_NAME: ${{ vars.MSSTORE_PACKAGE_IDENTITY_NAME }}
          MSSTORE_PUBLISHER: ${{ vars.MSSTORE_PUBLISHER }}
        run: ./scripts/build-msix.ps1

      - name: Upload MSIX artifact
        uses: actions/upload-artifact@v4
        with:
          name: tydora-msix
          path: src-tauri/target/msix/*.msix
          if-no-files-found: error

      - name: Attach MSIX to GitHub Release
        if: startsWith(github.ref, 'refs/tags/v')
        uses: softprops/action-gh-release@v2
        with:
          files: src-tauri/target/msix/*.msix

      # ── 发布到微软商店（仅当配置了 MSSTORE_PRODUCT_ID 时执行）──────────────
      - name: Setup Microsoft Store CLI
        if: vars.MSSTORE_PRODUCT_ID
        uses: microsoft/microsoft-store-apppublisher@v1.1

      - name: Reconfigure store credentials
        if: vars.MSSTORE_PRODUCT_ID
        shell: pwsh
        run: |
          msstore reconfigure `
            --tenantId ${{ secrets.AZURE_AD_TENANT_ID }} `
            --sellerId ${{ secrets.SELLER_ID }} `
            --clientId ${{ secrets.AZURE_AD_APPLICATION_CLIENT_ID }} `
            --clientSecret ${{ secrets.AZURE_AD_APPLICATION_SECRET }}

      - name: Publish package to Store
        if: vars.MSSTORE_PRODUCT_ID
        shell: pwsh
        run: |
          $msix = Get-ChildItem src-tauri/target/msix/*.msix | Select-Object -First 1
          Write-Host "Publishing: $($msix.FullName)"
          msstore publish $msix.FullName -id ${{ vars.MSSTORE_PRODUCT_ID }}
