name: Release

on:
  push:
    branches:
      - main
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      packages: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v3
        with:
          fetch-depth: 0  # Fetch all history for release notes

      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 18
          registry-url: https://npm.pkg.github.com

      - name: Cache npm dependencies
        uses: actions/cache@v3
        id: npm-cache
        with:
          path: ~/.npm
          key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-npm-

      - name: Cache pnpm dependencies
        uses: actions/cache@v3
        id: pnpm-cache
        with:
          path: ~/.pnpm-store
          key: ${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}
          restore-keys: |
            ${{ runner.os }}-pnpm-

      - name: Install dependencies
        run: npm ci

      - name: Run build
        run: npm run build

      - name: Test
        run: npm test

      - name: Get package version
        id: get_version
        run: echo "version=$(node -p "require('./package.json').version")" >> $GITHUB_OUTPUT
        
      - name: Generate Release Notes
        id: release_notes
        run: |
          RELEASE_NOTES=$(git log $(git describe --tags --abbrev=0 2>/dev/null || echo HEAD^)..HEAD --pretty=format:"- %s")
          echo "notes=${RELEASE_NOTES//$'\n'/%0A}" >> $GITHUB_OUTPUT

      - name: Create GitHub Release
        if: success()
        run: |
          echo "${{ steps.release_notes.outputs.notes }}" > release_notes.txt
          gh release create v${{ steps.get_version.outputs.version }} \
            --title "Release v${{ steps.get_version.outputs.version }}" \
            --notes-file release_notes.txt
        env:
          GH_TOKEN: ${{ github.token }}

      - name: Publish to npm registry
        if: success()
        env:
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: |
          echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > .npmrc
          npm publish --access public
          echo "Release published to npm package registry"

