steps:
  # Setup Node.js, npm authentication, and install build tools
  - template: setup-build-tools.yml@self

  - task: Bash@3
    displayName: "Build extension"
    inputs:
      targetType: "inline"
      script: |
        set -euo pipefail
        cd $(Build.SourcesDirectory)
        $(YARN_BIN) build --prod

  - task: Bash@3
    displayName: "Generate Unique Version"
    inputs:
      targetType: "inline"
      script: |
        # Use tag as version
        VERSION=${BUILD_SOURCEBRANCH#refs/tags/}
        echo "##vso[task.setvariable variable=VERSION]$VERSION"
        echo "Generated version: $VERSION"

  - task: Bash@3
    displayName: "Package all VSIX (generic + platforms)"
    inputs:
      targetType: "inline"
      script: |
        set -euo pipefail
        npm version --no-git-tag-version ${VERSION#v} || echo "Version unchanged, continuing."
        echo "Packaging generic + runtime VSIX variants"
        $(YARN_BIN) gulp package:platforms
        echo "Copying all produced VSIX to artifact staging directory"
        mkdir -p $(Build.ArtifactStagingDirectory)
        count=0
        for f in vscode-pgsql-*.vsix; do
          [ -f "$f" ] || continue
            cp -f "$f" "$(Build.ArtifactStagingDirectory)/"
            count=$((count+1))
        done
        # Copy artifact manifest if present
        if [ -f packaged-artifacts.json ]; then
          cp packaged-artifacts.json $(Build.ArtifactStagingDirectory)/
        fi
        echo "Copied $count VSIX files"
        ls -1 $(Build.ArtifactStagingDirectory)
        # Enforce expected count (1 generic + 6 runtime = 7)
        if [ "$count" -ne 7 ]; then
          echo "ERROR: Expected 7 VSIX files (1 generic + 6 runtime) but found $count" >&2
          exit 1
        fi

  - task: Bash@3
    displayName: "Generate per-VSIX manifests"
    inputs:
      targetType: "inline"
      script: |
        set -euo pipefail
        cd $(Build.ArtifactStagingDirectory)
        echo "Generating manifest JSON for each VSIX"
        for f in vscode-pgsql-*.vsix; do
          [ -f "$f" ] || continue
          out="${f}.manifest.json"
          "$(VSCE_BIN)" generate-manifest -i "$f" -o "$out"
        done
        echo "Manifests generated:"; ls -1 *.manifest.json || true

  - task: Bash@3
    displayName: "Prepare manifest signature placeholders"
    inputs:
      targetType: "inline"
      script: |
        set -euo pipefail
        cd $(Build.ArtifactStagingDirectory)
        for m in *.manifest.json; do
          [ -f "$m" ] || continue
          cp "$m" "${m%.json}.signature.p7s"
        done
        echo "Signature placeholders:"; ls -1 *.signature.p7s || true

  # Sign every manifest placeholder (glob support enabled)
  - task: onebranch.pipeline.signing@1
    displayName: "Sign all manifests"
    inputs:
      command: "sign"
      cp_code: CP-401405-VSCodePublisherSign
      files_to_sign: "**/*.signature.p7s"
      search_root: $(Build.ArtifactStagingDirectory)
