name: Release

on:
  push:
    branches:
      - main # or whatever branch you want to use

jobs:
  release:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v5

      - name: Check for changes in package.json
        run: |
          git diff --cached --diff-filter=d package.json || {
            echo "No changes to package.json"
            exit 1
          }

      - name: Get version number from package.json
        id: get_version
        run: |
          VERSION=$(jq -r '.version' package.json)
          echo "::set-output name=version::$VERSION"

      - name: Extract latest CHANGELOG entry
        run: |
          VERSION="${{ steps.get_version.outputs.version }}"
          awk "/^## \[${VERSION}\]/{found=1; next} /^## \[/{if(found) exit} found{print}" CHANGELOG.md > /tmp/release-notes.md

      - name: Create GitHub release
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          gh release create "v${{ steps.get_version.outputs.version }}" \
            --title "v${{ steps.get_version.outputs.version }}" \
            --notes-file /tmp/release-notes.md

      - name: Upload package to GitHub release
        uses: actions/upload-artifact@v4
        with:
          name: package
          path: |
            .
            !.git
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Trigger Docker build workflow
        uses: actions/github-script@v8
        with:
          script: |
            github.rest.actions.createWorkflowDispatch({
              owner: context.repo.owner,
              repo: context.repo.repo,
              workflow_id: 'docker-build.yaml',
              ref: 'v${{ steps.get_version.outputs.version }}',
            })
