name: Release

on:
  push:
    branches:
      - master

concurrency: ${{ github.workflow }}-${{ github.ref }}

permissions:
  contents: write
  pull-requests: write
  statuses: read
  deployments: write
  id-token: write

jobs:
  publish:
    runs-on: ubuntu-latest
    env:
      NODE_OPTIONS: --max-old-space-size=4096
    outputs:
      published: ${{ steps.changesets.outputs.published }}
    steps:
      - uses: actions/checkout@v4

      - name: Install PNPM
        uses: pnpm/action-setup@v3
        with:
          version: 9.4.0

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version-file: '.nvmrc'
          cache: 'pnpm'

      - name: Install
        run: pnpm install --frozen-lockfile --strict-peer-dependencies

      - name: Prepare release version
        id: pre_release
        run: |
          RELEASE_VER=$(pnpm changeset status --output=./release.json && node scripts/ci/release-version.js | tail -n 1)
          echo "version=${RELEASE_VER}" >> $GITHUB_OUTPUT

      - name: Creating .npmrc
        run: |
          cat << EOF > "$HOME/.npmrc"
            //registry.npmjs.org/:_authToken=$NPM_TOKEN
          EOF
        env:
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Create Release Pull Request or Publish to npm
        id: changesets
        uses: changesets/action@v1
        with:
          title: 'chore(release): publish ${{ steps.pre_release.outputs.version }}'
          publish: pnpm release
          commit: 'chore(release): release'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
