name: mocktail-cli

on:
  push:
    branches:
      - main  # or your default branch

permissions:
  contents: write

jobs:
  publish:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
      
      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 18
          registry-url: 'https://registry.npmjs.org'

      - name: Install dependencies
        run: npm install

      - name: Run tests
        run: npm test

      - name: Auto-patch version for unscoped package
        run: |
          # Get current published version
          CURRENT_VERSION=$(npm view mocktail-cli version 2>/dev/null || echo "0.0.0")
          echo "Current published version: $CURRENT_VERSION"
          
          # Get local version
          LOCAL_VERSION=$(node -p "require('./package.json').version")
          echo "Local version: $LOCAL_VERSION"
          
          # If versions are the same, patch the local version
          if [ "$CURRENT_VERSION" = "$LOCAL_VERSION" ]; then
            npm version patch --no-git-tag-version
            echo "Patched version to $(node -p "require('./package.json').version")"
          fi

      - name: Sync scoped package version
        run: |
          # Get the updated version from main package.json
          NEW_VERSION=$(node -p "require('./package.json').version")
          echo "Syncing scoped package to version: $NEW_VERSION"
          
          # Update scoped package version
          node -e "
            const fs = require('fs');
            const pkg = JSON.parse(fs.readFileSync('package.scoped.json', 'utf8'));
            pkg.version = '$NEW_VERSION';
            fs.writeFileSync('package.scoped.json', JSON.stringify(pkg, null, 2));
          "

      - name: Commit version changes
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
          git add package.json package.scoped.json
          git diff --staged --quiet || git commit -m "Auto-patch version to $(node -p "require('./package.json').version")"
          git push https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git HEAD:main

      - name: Publish unscoped package (mocktail-cli)
        run: npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.MOCKTAIL_CLI_CI_TOKEN }}

      - name: Publish scoped package (@mockilo/mocktail-cli)
        run: |
          cp package.scoped.json package.json
          npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.MOCKTAIL_CLI_CI_TOKEN }}
