name: Publish to npm

on:
  push:
    tags:
      - 'v*'  # Trigger on version tags (v2.2.3, v3.0.0, etc.)

jobs:
  publish:
    runs-on: ubuntu-latest

    permissions:
      contents: write  # For creating GitHub releases

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          registry-url: 'https://registry.npmjs.org'

      - name: Setup Bun
        uses: oven-sh/setup-bun@v2
        with:
          bun-version: latest

      - name: Install dependencies
        run: bun install

      - name: Build package
        run: bun run build

      - name: Sync version from VERSION file
        run: node scripts/sync-version.js

      - name: Verify package.json version
        run: |
          VERSION=$(cat VERSION)
          PKG_VERSION=$(node -p "require('./package.json').version")
          echo "VERSION file: $VERSION"
          echo "package.json: $PKG_VERSION"
          if [ "$VERSION" != "$PKG_VERSION" ]; then
            echo "Error: Version mismatch"
            exit 1
          fi

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

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ github.ref_name }}
          name: Release ${{ github.ref_name }}
          body: |
            ## Installation
            ```bash
            npm install -g @kaitranntt/ccs
            ```

            ## What's Changed
            See [CHANGELOG.md](https://github.com/kaitranntt/ccs/blob/main/CHANGELOG.md)
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}