name: Auto Release on Version Change

on:
  push:
    branches: [ main ]
    paths: [ 'package.json' ]

jobs:
  check-version:
    runs-on: ubuntu-latest
    outputs:
      version-changed: ${{ steps.version-check.outputs.changed }}
      new-version: ${{ steps.version-check.outputs.version }}
      version-tag: ${{ steps.version-check.outputs.tag }}
    
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 2
          
      - name: Check if version changed
        id: version-check
        run: |
          # Get current version from package.json
          CURRENT_VERSION=$(node -p "require('./package.json').version")
          echo "Current version: $CURRENT_VERSION"
          
          # Get previous version from package.json in the previous commit
          PREVIOUS_VERSION=$(git show HEAD~1:package.json | node -p "JSON.parse(require('fs').readFileSync('/dev/stdin').toString()).version")
          echo "Previous version: $PREVIOUS_VERSION"
          
          # Check if version changed
          if [ "$CURRENT_VERSION" != "$PREVIOUS_VERSION" ]; then
            echo "Version changed from $PREVIOUS_VERSION to $CURRENT_VERSION"
            echo "changed=true" >> $GITHUB_OUTPUT
            echo "version=$CURRENT_VERSION" >> $GITHUB_OUTPUT
            echo "tag=v$CURRENT_VERSION" >> $GITHUB_OUTPUT
          else
            echo "Version unchanged"
            echo "changed=false" >> $GITHUB_OUTPUT
          fi

  create-release:
    needs: check-version
    if: needs.check-version.outputs.version-changed == 'true'
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18'
          registry-url: 'https://registry.npmjs.org'
          
      - name: Install dependencies
        run: npm ci
        
      - name: Install admin dependencies
        working-directory: ./lib/admin
        run: npm ci
        
      - name: Build admin UI
        working-directory: ./lib/admin
        run: npm run build
        
      - name: Generate release notes
        id: release-notes
        run: |
          # Get commit messages since last tag
          LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
          
          if [ -n "$LAST_TAG" ]; then
            COMMITS=$(git log ${LAST_TAG}..HEAD --pretty=format:"- %s" --no-merges)
          else
            COMMITS=$(git log --pretty=format:"- %s" --no-merges -10)
          fi
          
          # Create release notes
          cat << EOF > release_notes.md
          # Release ${{ needs.check-version.outputs.new-version }}
          
          ## Changes
          
          $COMMITS
          
          ## Installation
          
          \`\`\`bash
          npm install @digitalnodecom/node-red-contrib-analyzer@${{ needs.check-version.outputs.new-version }}
          \`\`\`
          
          ## Dashboard
          
          After installation, access the analyzer dashboard at: \`http://localhost:1880/analyzer\`
          EOF
          
      - name: Create Git tag
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
          git tag ${{ needs.check-version.outputs.version-tag }}
          git push origin ${{ needs.check-version.outputs.version-tag }}
          
      - name: Create GitHub Release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: ${{ needs.check-version.outputs.version-tag }}
          release_name: ${{ needs.check-version.outputs.new-version }}
          body_path: release_notes.md
          draft: false
          prerelease: false
          
      - name: Publish to NPM
        run: npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
          
      - name: Add release comment
        uses: actions/github-script@v7
        with:
          script: |
            const { data: commits } = await github.rest.repos.listCommits({
              owner: context.repo.owner,
              repo: context.repo.repo,
              per_page: 1
            });
            
            if (commits.length > 0) {
              await github.rest.repos.createCommitComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                commit_sha: commits[0].sha,
                body: `🚀 **Auto Release Triggered**\n\nVersion **${{ needs.check-version.outputs.new-version }}** has been automatically:\n- ✅ Tagged as \`${{ needs.check-version.outputs.version-tag }}\`\n- ✅ Published to NPM\n- ✅ GitHub Release created\n\n[View Release](https://github.com/${{ github.repository }}/releases/tag/${{ needs.check-version.outputs.version-tag }})`
              });
            }