name: Publish to npm

on:
  push:
    branches:
      - main

jobs:
  publish:
    runs-on: ubuntu-latest
    concurrency:
      group: npm-publish
      cancel-in-progress: false

    steps:
      - name: Checkout
        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 --ignore-scripts

      - name: Build
        run: npm run build

      - name: Check version is not already published
        run: |
          PKG_VERSION=$(node -p "require('./package.json').version")
          NPM_VERSION=$(npm view react-native-mask-segment-canvas version 2>/dev/null || echo "0.0.0")
          if [ "$PKG_VERSION" = "$NPM_VERSION" ]; then
            echo "Error: version $PKG_VERSION already exists on npm. Please bump the version in package.json."
            exit 1
          fi
          echo "Publishing version $PKG_VERSION (npm latest: $NPM_VERSION)"

      - name: Publish to npm
        run: npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
