name: Rust CI & Publish

on:
  push:
    branches: [ "main" ]
    tags:
      - 'v*' # Triggers the publish job whenever you push a version tag like v0.1.0
  pull_request:
    branches: [ "main" ]

env:
  CARGO_TERM_COLOR: always

jobs:
  # Job 1: Runs on every push or pull request to make sure the library compiles perfectly
  build-and-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install Stable Rust Toolchain
        uses: dtolnay/rust-toolchain@stable
      - name: Build
        run: cargo build --verbose
      - name: Run tests
        run: cargo test --verbose

  # Job 2: Runs ONLY when you push a version tag (e.g. v0.1.0) and depend on the tests passing
  publish:
    needs: build-and-test
    if: startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install Stable Rust Toolchain
        uses: dtolnay/rust-toolchain@stable
      - name: Publish to Crates.io
        run: cargo publish --token ${{ secrets.CRATES_TOKEN }} --allow-dirty
