name: Release

on:
  pull_request:
    branches:
      - master
  push:
    branches:
      - master

permissions:
  contents: write
  pull-requests: write
  id-token: write

jobs:
  test:
    name: Test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: pnpm
      - run: pnpm install --frozen-lockfile
      - run: pnpm test

  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: pnpm
      - run: pnpm install --frozen-lockfile
      - run: pnpm build

  release:
    name: Release Please
    if: github.event_name == 'push'
    needs:
      - build
      - test
    runs-on: ubuntu-latest
    outputs:
      release_created: ${{ steps.release.outputs.release_created }}
    steps:
      - uses: googleapis/release-please-action@v4
        id: release
        with:
          token: ${{ secrets.RELEASE_PLEASE_TOKEN }}
          release-type: node
          target-branch: master

  publish:
    name: NPM Publish
    needs: release
    runs-on: ubuntu-latest
    if: ${{ needs.release.outputs.release_created }}
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: pnpm
          registry-url: "https://registry.npmjs.org"
      - run: npm --version
      - run: pnpm install --frozen-lockfile
      - run: pnpm build
      - run: cd dist && npm publish --provenance --access public

  docs:
    name: Deploy Documentation
    needs: release
    runs-on: ubuntu-latest
    if: ${{ needs.release.outputs.release_created }}
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: pnpm
      - run: pnpm install --frozen-lockfile
      - run: cd docs && pnpm install --frozen-lockfile
      - run: pnpm docs:build
      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v4
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./docs/build
