name: Go Benchmark

on:
  push:
    branches:
      - main
      - development
    paths:
      - 'backend/**'
  pull_request:
    branches:
      - main
      - development
    paths:
      - 'backend/**'
  workflow_dispatch:

permissions:
  contents: write
  deployments: write

jobs:
  benchmark:
    name: Performance Regression Check
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6

      - name: Set up Go
        uses: actions/setup-go@4dc6199c7b1a012772edbd06daecab0f50c9053c # v6
        with:
          go-version: '1.25.5'
          cache-dependency-path: backend/go.sum

      - name: Run Benchmark
        working-directory: backend
        run: go test -bench=. -benchmem -run='^$' ./... | tee output.txt

      - name: Store Benchmark Result
        # Only store results on pushes to main - PRs just run benchmarks without storage
        # This avoids gh-pages branch errors and permission issues on fork PRs
        if: github.event_name == 'push' && github.ref == 'refs/heads/main'
        uses: benchmark-action/github-action-benchmark@v1
        with:
          name: Go Benchmark
          tool: 'go'
          output-file-path: backend/output.txt
          github-token: ${{ secrets.GITHUB_TOKEN }}
          auto-push: true
          # Show alert with commit comment on detection of performance regression
          # Threshold increased to 175% to account for CI variability
          alert-threshold: '175%'
          comment-on-alert: true
          fail-on-alert: false
          # Enable Job Summary
          summary-always: true

      - name: Run Perf Asserts
        working-directory: backend
        env:
          PERF_MAX_MS_GETSTATUS_P95: 500ms
          PERF_MAX_MS_GETSTATUS_P95_PARALLEL: 1500ms
          PERF_MAX_MS_LISTDECISIONS_P95: 2000ms
        run: |
          echo "## 🔍 Running performance assertions (TestPerf)" >> $GITHUB_STEP_SUMMARY
          go test -run TestPerf -v ./internal/api/handlers -count=1 | tee perf-output.txt
          exit ${PIPESTATUS[0]}
