name: CI

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    
    strategy:
      matrix:
        node-version: [18.x, 20.x]
    
    steps:
    - uses: actions/checkout@v3
    
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v3
      with:
        node-version: ${{ matrix.node-version }}
        cache: 'npm'
    
    - name: Install dependencies
      run: npm ci
    
    - name: Run lint
      run: npm run lint
    
    - name: Run type check
      run: npm run check
    
    - name: Run tests
      run: npm test
    
    - name: Build
      run: npm run build

  release:
    needs: test
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main' && github.event_name == 'push'
    
    steps:
    - uses: actions/checkout@v3
    
    - name: Use Node.js 20.x
      uses: actions/setup-node@v3
      with:
        node-version: 20.x
        cache: 'npm'
        registry-url: 'https://registry.npmjs.org'
    
    - name: Install dependencies
      run: npm ci
    
    - name: Build
      run: npm run build
    
    - name: Check if version changed
      id: version
      run: |
        CURRENT_VERSION=$(node -p "require('./package.json').version")
        echo "current_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT
        
        # Check if this version exists on npm
        if npm view repomirror@$CURRENT_VERSION version 2>/dev/null; then
          echo "version_exists=true" >> $GITHUB_OUTPUT
        else
          echo "version_exists=false" >> $GITHUB_OUTPUT
        fi
    
    - name: Publish to npm
      if: steps.version.outputs.version_exists == 'false'
      run: npm publish
      env:
        NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}