name: Release and Publish to NPM

on:
  push:
    branches:
      - main
  pull_request:
    types: [closed]
    branches:
      - main
  release: 
    types: [published]

permissions:
  contents: write
  packages: write
  id-token: write

jobs:
  release:
    runs-on: ubuntu-latest

    steps:
      # Step 1: Checkout repository
      - name: Checkout repository
        uses: actions/checkout@v4

      # Step 2: Set up Node.js
      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          # cache: 'npm'

      # Step 3: Install dependencies
      - name: Install dependencies
        run: npm install


      # Step 5: Build the project
      - name: Build project
        run: npm run build

      # Step 6: Authenticate with npm registry
      - name: Authenticate with npm registry
        run: echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" > ~/.npmrc

      # Step 7: Publish package to npm
      - name: Publish to npm
        run: npx changeset publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      # Step 8: Commit and push changesets version bump
      - name: Commit and Push Changes
        if: steps.changesets.outputs.has_changes == 'true'
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add .
          git commit -m "chore: version bump via changesets"
          git push origin main
