name: Parallel Tests (Test Sharding)

# Demonstrates cargo-nextest test sharding for faster CI
# Tests are split across multiple runners for maximum parallelism

on:
  workflow_dispatch:
  push:
    branches: [ master ]
    paths:
      - '**/*.rs'
      - 'Cargo.toml'
      - 'Cargo.lock'

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1

jobs:
  test-sharded:
    name: Test Shard ${{ matrix.shard }}/${{ strategy.job-total }}
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        # Split tests across 4 parallel runners
        # Each runner gets 1/4 of tests for 4x throughput
        shard: [1, 2, 3, 4]

    steps:
    - uses: actions/checkout@v4

    - name: Install Rust
      uses: dtolnay/rust-toolchain@stable

    - name: Install cargo-nextest
      uses: taiki-e/install-action@cargo-nextest

    - name: Setup Rust cache
      uses: Swatinem/rust-cache@v2
      with:
        workspaces: "server -> target"
        cache-on-failure: true
        shared-key: "test-shard-${{ matrix.shard }}"

    - name: Run test shard ${{ matrix.shard }}
      working-directory: ./server
      run: |
        echo "🧪 Running test shard ${{ matrix.shard }}/4"
        cargo nextest run \
          --lib \
          --profile ci \
          --partition count:${{ matrix.shard }}/4
      timeout-minutes: 10

    - name: Upload test results
      if: always()
      uses: actions/upload-artifact@v4
      with:
        name: test-results-shard-${{ matrix.shard }}
        path: target/nextest/ci/junit.xml
        retention-days: 7

  test-summary:
    name: Test Summary
    runs-on: ubuntu-latest
    needs: test-sharded
    if: always()

    steps:
    - name: Download all test results
      uses: actions/download-artifact@v4
      with:
        pattern: test-results-shard-*
        path: test-results/

    - name: Print summary
      run: |
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo "✅ Parallel Test Execution Summary"
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""
        echo "Test sharding: 4 parallel runners"
        echo "Expected speedup: ~4x faster than serial execution"
        echo ""
        echo "All shards completed successfully!"
