name: CI

on:
  push:
    branches:
      - master
    tags:
      - "v[0-9]+.[0-9]+.[0-9]+"
  pull_request:

permissions:
    contents: write
    pull-requests: write
    id-token: write

jobs:
    ci:
        runs-on: ubuntu-latest
        permissions:
            id-token: write # for npm publish
            actions: read # for Nerivec/action-ci-bench
        steps:
            - uses: actions/checkout@v6

            - uses: pnpm/action-setup@v6

            - uses: actions/setup-node@v6
              with:
                  node-version: 24
                  registry-url: https://registry.npmjs.org/
                  cache: pnpm

            - name: Install dependencies
              run: pnpm i --frozen-lockfile

            - name: Check
              run: pnpm run check

            - name: Build
              run: pnpm run build

            - name: Test
              run: pnpm run test:coverage -- --testTimeout=10000

            - name: Bench
              if: github.ref == 'refs/heads/master' || (github.event_name == 'pull_request' && !startsWith(github.head_ref, 'release-please-'))
              uses: Nerivec/action-ci-bench@main
              with:
                token: ${{ secrets.GITHUB_TOKEN }}
                compare-against: master
                base-cmd: npx vitest bench --run --config ./test/vitest.config.mts --outputJson bench.json
                compare-cmd: npx vitest bench --run --config ./test/vitest.config.mts --compare bench.json
                base-result: bench.json

            - name: Publish new release
              if: startsWith(github.ref, 'refs/tags/') && github.event_name == 'push'
              run: |
                  pnpm publish --no-git-checks
                  PACKAGE=$(node -p "require('./package.json').name")
                  VERSION=$(node -p "require('./package.json').version")
                  until [ $(pnpm view $PACKAGE --json | jq --arg version "$VERSION" -r '.versions[] | select (. == $version)') ];
                  do
                    echo "Waiting for publish to complete"
                    sleep 5s
                  done
                  curl -XPOST -H "Authorization: token ${{ secrets.GH_TOKEN }}" -H "Accept: application/vnd.github.everest-preview+json" -H "Content-Type: application/json" https://api.github.com/repos/koenkk/zigbee2mqtt/dispatches --data "{\"event_type\": \"update_dep\", \"client_payload\": { \"version\": \"$VERSION\", \"package\": \"$PACKAGE\"}}"
              env:
                  NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN }}
                  NPM_CONFIG_PROVENANCE: true
