name: CI

on:
  push:

permissions:
  contents: write

jobs:
  test:
    strategy:
      matrix:
        os: [ubuntu-latest, macos-latest]
        go-version: ['1.25.0']
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v5
        with:
          fetch-depth: 0

      - name: Set up Go
        uses: actions/setup-go@v6
        with:
          go-version: ${{ matrix.go-version }}

      - name: Cache Go modules
        uses: actions/cache@v4
        with:
          path: |
            ~/.cache/go-build
            ~/go/pkg/mod
          key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
          restore-keys: |
            ${{ runner.os }}-go-

      - name: Install dependencies and tools
        run: make deps

      - name: Run tests
        run: make test

      - name: Run linter
        run: make lint

      - name: Test with coverage
        run: make cover

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v5.5.1
        with:
          fail_ci_if_error: true
          file: ./coverage.out
          token: ${{ secrets.CODECOV_TOKEN }}
          verbose: true

      - name: Check coverage threshold
        if: matrix.os == 'ubuntu-latest'
        run: |
          total=$(go tool cover -func=coverage.out | grep total | awk '{print substr($3, 1, length($3)-1)}')
          threshold=80.0
          awk "BEGIN {exit !(total < threshold)}" && \
            echo "Coverage $total% is below threshold $threshold%" && exit 1 || \
            echo "Coverage $total% is above threshold $threshold%"

      - name: Build
        run: make build
