name: Build and Test

on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

      - name: Download dependencies
        run: go mod download

      - name: Run tests with coverage
        run: |
          go test -race -coverprofile=coverage.txt -covermode=atomic ./...
          TOTAL=$(go tool cover -func=coverage.txt | grep total | awk '{gsub(/%/, "", $3); print $3}')
          echo "Coverage: ${TOTAL}%"
          if (( $(echo "$TOTAL < 80" | bc -l) )); then
            echo "Coverage ${TOTAL}% is below 80% threshold"
            exit 1
          fi

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v3
        with:
          file: ./coverage.txt

  build:
    runs-on: ubuntu-latest
    needs: test
    steps:
      - uses: actions/checkout@v4

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

      - name: Build binary
        run: |
          CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
            -ldflags="-w -s" \
            -o logcorrelator \
            ./cmd/logcorrelator

      - name: Upload binary artifact
        uses: actions/upload-artifact@v4
        with:
          name: logcorrelator-linux-amd64
          path: logcorrelator

  docker:
    runs-on: ubuntu-latest
    needs: test
    steps:
      - uses: actions/checkout@v4

      - name: Build Docker image
        run: docker build -t logcorrelator:latest .

      - name: Run tests in Docker
        run: |
          docker run --rm logcorrelator:latest --help || true
