name: Publish Release

on:
  release:
    types: [published]

permissions:
  contents: read

jobs:
  publish-release:
    name: Publish Release
    runs-on: ubuntu-latest
    steps:
      - name: Setup Node.js Environment
        uses: actions/setup-node@v4
        with:
          node-version: 22.21.1

      - name: Run node-gyp bug workaround script
        run: |
          curl -sSfLO https://raw.githubusercontent.com/mongodb-js/compass/42e6142ae08be6fec944b80ff6289e6bcd11badf/.evergreen/node-gyp-bug-workaround.sh && bash node-gyp-bug-workaround.sh

      - name: Install VSCode publishing dependencies
        run: npm install -g vsce

      - name: Download release assets
        run: |
          filename=$(basename -- "$ASSET_URL")
          extension="${filename##*.}"

          if [[ $extension != "vsix" ]]; then
            echo "Wrong asset extension ${extension} in ${ASSET_URL}"
            exit 1
          else
            wget -O ${filename} "${ASSET_URL}"
            ls -al ${filename}
            echo "VSIX_PATH=${filename}" >> $GITHUB_ENV
          fi
        env:
          ASSET_URL: ${{ github.event.release.assets[0].browser_download_url }}

      - name: Publish to marketplace
        run: |
          echo "Publishing ${VSIX_PATH} to marketplace"
          npx vsce publish --packagePath "${VSIX_PATH}" --githubBranch main
        env:
          VSCE_PAT: ${{ secrets.VSCE_PAT }}
