# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
# For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages

name: Publish to GitHub

on:
  repository_dispatch:
    types: [commit-change]

jobs:
  publish-github:
    name: Publish to GitHub
    runs-on: ubuntu-latest
    permissions:
      packages: write
      contents: read
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.client_payload.tag_name }}

      - name: Get package manager config to output
        id: package_manager
        run: |
          if [ -z "${{ vars.PACKAGE_MANAGER || env.PACKAGE_MANAGER || secrets.PACKAGE_MANAGER }}" ]; then
            echo "PACKAGE_MANAGER=yarn" >> "$GITHUB_ENV"
          else
            echo "PACKAGE_MANAGER=${{ vars.PACKAGE_MANAGER || env.PACKAGE_MANAGER || secrets.PACKAGE_MANAGER }}" >> "$GITHUB_ENV"
          fi
  
      - uses: pnpm/action-setup@v3
        if: ${{ env.PACKAGE_MANAGER == 'pnpm' }}
        with:
          version: 8

      - uses: actions/setup-node@v4
        with:
          node-version: '20.x'
          registry-url: https://npm.pkg.github.com/
          cache: ${{ (env.PACKAGE_MANAGER == 'pnpm' && hashFiles('pnpm-lock.yaml') && 'pnpm') || (env.PACKAGE_MANAGER == 'yarn' && hashFiles('yarn.lock') && 'yarn') || (env.PACKAGE_MANAGER == 'npm' && hashFiles('package-lock.json') && 'npm') || '' }}

      - run: npm pkg set name="@${{ github.repository_owner }}/${{ github.event.repository.name }}"

      - name: Reinstall to reflect new name
        run: |
          if [ "${{ env.PACKAGE_MANAGER }}" == "npm" ]; then
            npm ci
          elif [ "${{ env.PACKAGE_MANAGER }}" == "pnpm" ]; then
            pnpm install --no-frozen-lockfile
          elif [ "${{ env.PACKAGE_MANAGER }}" == "yarn" ]; then
            yarn install --no-immutable
          fi

      - name: Publish
        run: |
          npm publish --registry=https://npm.pkg.github.com
        env:
          NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}