name: Publish on Release

on:
  release:
    types: [published]

jobs:
  # Runs the full test suite against React 17 and 18 before any publish step.
  # Both matrix jobs must pass — if any fail, the publish job never runs.
  # React 19 is excluded until pull-to-refresh setState/act compatibility is fixed.
  validate:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: true
      matrix:
        react: ['17', '18']
    steps:
      - uses: actions/checkout@v4

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: 20.x
          cache: 'yarn'

      - name: Install dependencies
        run: yarn install --frozen-lockfile

      - name: Swap to React ${{ matrix.react }}
        run: |
          yarn add --dev react@${{ matrix.react }} react-dom@${{ matrix.react }}

      - name: Type check
        run: yarn ts-check

      - name: Unit tests
        run: yarn test --runInBand

  publish:
    needs: validate
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write

    steps:
      - uses: actions/checkout@v4

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: 20.x
          cache: 'yarn'
          registry-url: 'https://registry.npmjs.org'

      - name: Install dependencies
        run: yarn install --frozen-lockfile

      - name: Build
        run: yarn build

      - name: Publish to npm
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }}
        run: |
          if [[ "${{ github.event.release.prerelease }}" == "true" ]]; then
            npm publish --access public --tag beta
          else
            npm publish --access public
          fi
