name: Backend CI

on:
  push:
    branches: [main, master]
    paths:
      - 'backend/**'
      - '.github/workflows/backend-ci.yml'
  pull_request:
    branches: [main, master]
    paths:
      - 'backend/**'
      - '.github/workflows/backend-ci.yml'
  workflow_dispatch:

env:
  CARGO_TERM_COLOR: always

jobs:
  check:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: backend

    steps:
      - uses: actions/checkout@v4

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy

      - name: Cache cargo
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/bin/
            ~/.cargo/registry/index/
            ~/.cargo/registry/cache/
            ~/.cargo/git/db/
            backend/target/
          key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}

      - name: Check formatting
        run: cargo fmt --all -- --check

      - name: Clippy
        run: cargo clippy --all-targets --all-features -- -W clippy::all
        continue-on-error: true  # Warnings from inherited code

      - name: Build
        run: cargo build --release

      - name: Run tests
        run: cargo test --release

  build-binaries:
    runs-on: ubuntu-latest
    needs: check
    defaults:
      run:
        working-directory: backend

    steps:
      - uses: actions/checkout@v4

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Cache cargo
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/bin/
            ~/.cargo/registry/index/
            ~/.cargo/registry/cache/
            ~/.cargo/git/db/
            backend/target/
          key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}

      - name: Build release binaries
        run: cargo build --release

      - name: Upload binaries
        uses: actions/upload-artifact@v4
        with:
          name: backend-binaries
          path: |
            backend/target/release/telemetry_core
            backend/target/release/telemetry_shard
          retention-days: 7
