name: Contracts CI
on:
  pull_request:
    branches:
      - dev
      - staging
      - main

concurrency:
  group: contracts-ci-${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  check_changes:
    runs-on: ubuntu-slim
    outputs:
      should_run: ${{ steps.filter.outputs.should_run }}
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Check if should run
        id: filter
        run: |
          set -e
          if [[ "${{ github.base_ref }}" == "main" ]] || [[ "${{ github.base_ref }}" == "staging" ]]; then
            echo "should_run=true" >> $GITHUB_OUTPUT
            echo "Running for ${{ github.base_ref }} - no path filter"
          else
            # For dev branch, check if contracts or common files changed
            CHANGED_FILES=$(git diff --name-only origin/${{ github.base_ref }}...HEAD) || {
              echo "Error: Failed to diff against base branch"
              exit 1
            }
            if echo "$CHANGED_FILES" | grep -qE "^(contracts|common)/"; then
              echo "should_run=true" >> $GITHUB_OUTPUT
              echo "Running for dev - contracts or common files changed"
            else
              echo "should_run=false" >> $GITHUB_OUTPUT
              echo "Skipping for dev - no contracts or common files changed"
            fi
          fi

  test_contracts:
    needs: check_changes
    if: github.event.pull_request.draft == false && needs.check_changes.outputs.should_run == 'true'
    runs-on: ubuntu-latest
    environment: development
    steps:
      - uses: actions/checkout@v6
      - name: Read and sanitize Node.js version
        shell: bash
        run: |
          if [ ! -f .nvmrc ] || [ -z "$(cat .nvmrc)" ]; then
            echo "❌ .nvmrc is missing or empty"; exit 1;
          fi
          VERSION="$(tr -d '\r\n' < .nvmrc)"
          VERSION="${VERSION#v}"
          if ! [[ "$VERSION" =~ ^[0-9]+(\.[0-9]+){0,2}$ ]]; then
            echo "Invalid .nvmrc content: '$VERSION'"; exit 1;
          fi
          echo "NODE_VERSION=$VERSION" >> "$GITHUB_ENV"
          echo "NODE_VERSION_SANITIZED=${VERSION//\//-}" >> "$GITHUB_ENV"
      - name: Set Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
      - name: Install Dependencies
        uses: ./.github/actions/yarn-install
      - name: Prettier Check - Code Formatting
        run: yarn prettier:check
        working-directory: ./contracts
      - name: Build Common Dependencies
        run: yarn workspace @selfxyz/common build
      - name: Build Contracts
        run: yarn build
        working-directory: ./contracts
      - name: Run Tests (Contracts)
        working-directory: ./contracts
        # skip until they get fixed
        if: false
        run: yarn test
