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

steps:
  - bash: |
      echo "Preparing GitHub release"
      echo "ReleaseVersion=$RELEASE_VERSION"
      echo "IsDevTag=$IS_DEV_TAG"
    displayName: Log release metadata
    env:
      RELEASE_VERSION: $(ReleaseVersion)
      IS_DEV_TAG: $(IsDevTag)

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

  - task: Bash@3
    displayName: "Validate artifact manifest"
    inputs:
      targetType: inline
      script: |
        set -euo pipefail
        manifestPath="$(Build.ArtifactStagingDirectory)/packaged-artifacts.json"
        if [ ! -f "$manifestPath" ]; then
          echo "ERROR: Artifact manifest not found (packaged-artifacts.json)." >&2
          exit 1
        fi
        echo "Artifact manifest contents:"; cat "$manifestPath"
        genericCount=$(jq '[ .[] | select(.kind=="generic") ] | length' "$manifestPath")
        if [ "$genericCount" -ne 1 ]; then
          echo "ERROR: Expected exactly 1 generic entry, found $genericCount" >&2
          exit 1
        fi
        runtimeCount=$(jq '[ .[] | select(.kind=="runtime") ] | length' "$manifestPath")
        if [ "$runtimeCount" -lt 1 ]; then
          echo "ERROR: Expected at least 1 runtime entry, found $runtimeCount" >&2
          exit 1
        fi
        # Enforce that every VSIX manifest has a corresponding signature file
        missing=0
        for file in $(jq -r '.[] | .file' "$manifestPath"); do
          sig="$(Build.ArtifactStagingDirectory)/${file}.manifest.signature.p7s"
          if [ ! -f "$sig" ]; then
            echo "ERROR: Missing signature file for $file -> ${file}.manifest.signature.p7s" >&2
            missing=$((missing+1))
          fi
        done
        if [ "$missing" -gt 0 ]; then
          echo "ERROR: $missing signature file(s) missing. Aborting release." >&2
          exit 1
        fi
        echo "Manifest validation passed: 1 generic, $runtimeCount runtime entries."

  - task: GithubRelease@1
    displayName: "Create GitHub Release"
    inputs:
      gitHubConnection: "Database Systems (3)"
      repositoryName: "azure-data-database-platform/vs-code-postgresql"
      tagSource: userSpecifiedTag
      tag: $(ReleaseVersion)
      title: $(ReleaseVersion)
      changeLogType: commitBased
      assets: |
        $(Build.ArtifactStagingDirectory)/*.vsix
      isPrerelease: $[eq(variables['GitHubIsPrerelease'], 'true')]
