# Name of the GitHub Actions workflow
name: Test (and Revert on Failure)
 
# Define when this workflow should run
on:
  push:
    branches: [ main ]  # Trigger on pushes to the main branch
  pull_request:
    branches: [ main ]  # Trigger on pull requests targeting the main branch
 
jobs:
  test:
    runs-on: ubuntu-latest
 
    steps:
    - uses: actions/checkout@v3
 
    - name: Use Node.js
      uses: actions/setup-node@v3
      with:
        node-version: '18'
 
    - name: Install dependencies
      run: npm ci
 
    - name: Run Vitest tests
      run: npm test
 
  # Auto-revert if the build or test fails
  auto-revert:
    needs: test  # This job depends on the 'test' job
    runs-on: ubuntu-latest
    if: failure()  # Only run this job if the 'test' job fails
 
    steps:
    - uses: actions/checkout@v3
      with:
        fetch-depth: 0  # Fetch all history for all branches and tags
 
    - name: Automatic Revert
      run: |
        git config user.name github-actions
        git config user.email github-actions@github.com
        git revert -m 1 HEAD
        git push
 
# Note: This workflow will automatically revert the last push to the main branch
# if the test job fails. It creates a new commit that undoes the changes
# from the failed push. This helps maintain a stable main branch by quickly
# reverting changes that break the tests.
 
# Caution: 
# 1. This approach assumes pushes are merge commits. Adjust if using direct pushes.
# 2. Concurrent pushes might cause conflicts. Additional error handling may be needed.
# 3. Make sure team members are aware of this auto-revert functionality to avoid confusion.