name: Run tests and upload coverage

on:
  push

jobs:
  test:
    name: Run tests and collect coverage
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Set up Node
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Install dependencies
        run: npm install

      - name: Build
        run: npm run build

      - name: Start test server
        run: |
          nohup npm start > /tmp/rexhr-test-server.log 2>&1 &
          echo $! > /tmp/rexhr-test-server.pid

      - name: Wait for server
        run: |
          for i in {1..30}; do
            if curl -fsS http://127.0.0.1:3001/save > /dev/null; then
              exit 0
            fi
            sleep 1
          done
          echo "Server did not become ready in time"
          echo "---- server log ----"
          cat /tmp/rexhr-test-server.log
          exit 1

      - name: Run tests
        run: npm run cover

      - name: Check Codecov token
        env:
          CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
        run: |
          if [ -z "$CODECOV_TOKEN" ]; then
            echo "Missing CODECOV_TOKEN secret"
            exit 1
          fi

      - name: Verify coverage files
        run: |
          ls -la coverage
          test -f coverage/lcov.info
          wc -l coverage/lcov.info
          head -n 20 coverage/lcov.info

      - name: Debug git metadata
        run: |
          git status --short
          git branch --show-current || true
          git rev-parse HEAD
          git log -1 --pretty=fuller

      - name: Upload results to Codecov
        if: always() && hashFiles('coverage/lcov.info') != ''
        uses: codecov/codecov-action@v4
        env:
          CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
        with:
          files: ./coverage/lcov.info
          disable_search: true
          fail_ci_if_error: true
          verbose: true

      - name: Stop test server
        if: always()
        run: |
          if [ -f /tmp/rexhr-test-server.pid ]; then
            kill "$(cat /tmp/rexhr-test-server.pid)" || true
          fi
