name: Publish

on:
  push:
    branches:
      - main

jobs:
  publish:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout code
      uses: actions/checkout@v4
      with:
        fetch-depth: 0

    - name: Set up Node.js
      uses: actions/setup-node@v3
      with:
        node-version: '18'
        registry-url: 'https://registry.npmjs.org'

    - name: Check if version exists on npm
      id: npm_version_check
      run: |
        # Get the current version from package.json
        current_version=$(jq -r '.version' package.json)
        echo "Current version: $current_version"
        package_name=$(jq -r '.name' package.json)
        echo "Package name: $package_name"
        
        # Check if the version exists on npm
        npm_info=$(npm view "$package_name@$current_version" version || echo "not_found")

        if [ "$npm_info" == "not_found" ]; then
          echo "Version $current_version does not exist on npm."
          echo "::set-output name=version_exists::false"
        else
          echo "Version $current_version already exists on npm."
          echo "::set-output name=version_exists::true"
        fi

    - name: Publish to NPM
      if: steps.npm_version_check.outputs.version_exists == 'false'
      env:
        NODE_AUTH_TOKEN: ${{ secrets.NPM_CI_TOKEN }}
      run: |
        npm publish

    - name: Create GitHub Release
      if: steps.npm_version_check.outputs.version_exists == 'false'
      env:
        GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      run: |
        current_version=${{ steps.version_check.outputs.current_version }}
        gh release create "v$current_version" \
          --title "Release v$current_version" \
          --generate-notes
