name: CI
run-name: "CI Pipeline"
on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    name: Test
    runs-on: ubuntu-latest
    strategy:
      matrix:
        go-version: ['1.22', '1.23']

    steps:
    - name: Checkout code
      uses: actions/checkout@v4

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

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

    - name: Download dependencies
      run: go mod download

    - name: Clean build cache
      run: |
        go clean -cache
        go mod tidy

    - name: Run unit tests
      run: make test

    - name: Upload coverage to Codecov
      uses: codecov/codecov-action@v4
      with:
        file: ./coverage.out
        flags: unittests
        name: codecov-umbrella

  lint:
    name: Lint
    runs-on: ubuntu-latest

    steps:
    - name: Checkout code
      uses: actions/checkout@v4

    - name: Set up Go
      uses: actions/setup-go@v5
      with:
        go-version: '1.25'

    - name: Install golangci-lint
      run: |
        curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin latest
        echo "$(go env GOPATH)/bin" >> $GITHUB_PATH

    - name: Run linter
      run: make lint

  build:
    name: Build
    runs-on: ubuntu-latest

    steps:
    - name: Checkout code
      uses: actions/checkout@v4

    - name: Set up Go
      uses: actions/setup-go@v5
      with:
        go-version: '1.25'

    - name: Download dependencies
      run: go mod download

    - name: Build binary
      run: make build

    - name: Verify binaries exist
      run: |
        if [ ! -f bin/whatshook-server ]; then
          echo "Error: Server binary not found at bin/whatshook-server"
          exit 1
        fi
        if [ ! -f bin/whatshook-cli ]; then
          echo "Error: CLI binary not found at bin/whatshook-cli"
          exit 1
        fi
        echo "Build successful!"
        ls -lh bin/

    - name: Check mod tidiness
      run: |
        go mod tidy
        git diff --exit-code go.mod go.sum
