parameters:
  - name: expectedVsixCount
    type: number
    default: 7

steps:
  - template: setup-build-tools.yml@self

  - bash: |
      echo "Preparing Marketplace publication"
      echo "ReleaseVersion=$RELEASE_VERSION"
      echo "IsDevTag=$IS_DEV_TAG"
      if [[ -n "$MARKETPLACE_RELEASE_TYPE" ]]; then
        echo "Marketplace release type: $MARKETPLACE_RELEASE_TYPE"
      elif [[ "$VSCE_PRE_RELEASE_FLAG" == "" ]]; then
        echo "Marketplace release type: STABLE"
      else
        echo "Marketplace release type: PRE-RELEASE"
      fi
    displayName: Log release metadata
    env:
      RELEASE_VERSION: $(ReleaseVersion)
      IS_DEV_TAG: $(IsDevTag)
      VSCE_PRE_RELEASE_FLAG: $(VscePreReleaseFlag)
      MARKETPLACE_RELEASE_TYPE: $(MarketplaceReleaseType)

  # Download and stage artifacts for publication
  - template: stage-release-artifacts.yml@self
    parameters:
      expectedVsixCount: ${{ parameters.expectedVsixCount }}

  - task: AzureCLI@2
    displayName: "Publish to VSCode Marketplace"
    env:
      VSCE_PRE_RELEASE_FLAG: $(VscePreReleaseFlag)
      VSCE_BIN: $(VSCE_BIN)
    inputs:
      azureSubscription: VS-Code-VSCE-MSFT
      scriptType: "pscore"
      scriptLocation: "inlineScript"
      inlineScript: |
        # === Marketplace Publication Script ===
        # This script publishes every VSIX listed in packaged-artifacts.json.
        # The manifest entries produced by packaging look like:
        #   [{
        #       "kind": "generic",
        #       "file": "vscode-pgsql-<ver>.vsix",
        #       "target": null
        #    }, {
        #       "kind": "runtime",
        #       "rid": "linux-x64",
        #       "file": "vscode-pgsql-<ver>-linux-x64.vsix",
        #       "target": "linux-x64"
        #    }, ...]
        # We iterate everything; runtime-specific packages have already been produced using
        # 'vsce package --target', so we publish the pre-built VSIX directly via --packagePath.
        # The pre-release flag ("--pre-release") is determined earlier based on odd minor version.

        Write-Host "Starting VSCode Marketplace publication..."
        $base = "$(Build.ArtifactStagingDirectory)"
        $preFlag = $env:VSCE_PRE_RELEASE_FLAG
        $manifestPath = Join-Path $base 'packaged-artifacts.json'

        # Fail fast if artifact manifest missing
        if (-not (Test-Path $manifestPath)) { Write-Error "Artifact manifest missing: $manifestPath" }

        # Read and parse JSON ( -Raw prevents per-line array )
        $json = Get-Content $manifestPath -Raw | ConvertFrom-Json
        if (-not $json) { Write-Error "Failed to parse artifact manifest JSON" }

        if (-not $env:VSCE_BIN) { Write-Error "VSCE_BIN pipeline variable not set" }
        $vscePath = $env:VSCE_BIN

        $count = 0
        foreach ($entry in $json) {
          # Validate required field
          $file = $entry.file
          if ([string]::IsNullOrWhiteSpace($file)) { Write-Error "Entry missing file property" }

          # Compose paths for VSIX and its per-artifact manifest / signature
          $filePath = Join-Path $base $file
          if (-not (Test-Path $filePath)) { Write-Error "VSIX missing: $filePath" }
          $manPath = Join-Path $base ($file + '.manifest.json')
          if (-not (Test-Path $manPath)) { Write-Error "Manifest missing for VSIX: $manPath" }

          $signaturePath = Join-Path $base ($file + '.manifest.signature.p7s')

          # Compose the full publish command for this artifact
          $cmdArgs = @("publish")
          if (-not [string]::IsNullOrWhiteSpace($preFlag)) {
            $cmdArgs += $preFlag
          }
          $cmdArgs += @(
            "--packagePath",
            $filePath,
            "--manifestPath",
            $manPath,
            "--azure-credential",
            "--signaturePath",
            $signaturePath
          )

          Write-Host "### Publishing artifact kind=$($entry.kind) file=$file target=$($entry.target)"
          Write-Host "Command: $vscePath $($cmdArgs -join ' ')"

          # Execute the vsce publish command
          & $vscePath @cmdArgs

          # Check exit code because call-operator (&) doesn't throw on non-zero exit
          if ($LASTEXITCODE -ne 0) {
            throw "vsce publish failed with exit code $LASTEXITCODE"
          }

          $count++
        }
        Write-Host "Publication completed successfully (processed $count artifacts)"
