name: Publish to crates.io

on:
  push:
    tags:
      - "v*"

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1
  CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
  FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true

jobs:
  test:
    name: Test
    runs-on: ubuntu-latest
    services:
      # Ryuk is disabled below; Docker daemon is available via the runner
      docker:
        image: docker:dind
        options: --privileged
    steps:
      - uses: actions/checkout@v6

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

      - name: Cache cargo registry
        uses: actions/cache@v5
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            target
          key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: ${{ runner.os }}-cargo-

      - name: Install cargo-llvm-cov
        uses: taiki-e/install-action@cargo-llvm-cov

      - name: Run tests with coverage
        env:
          TESTCONTAINERS_RYUK_DISABLED: "true"
        run: cargo llvm-cov --all-features --lcov --output-path lcov.info

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v5
        with:
          files: lcov.info
          fail_ci_if_error: true
          token: ${{ secrets.CODECOV_TOKEN }}

  publish:
    name: Publish
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

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

      - name: Verify version matches tag
        run: |
          TAG="${GITHUB_REF_NAME#v}"
          CRATE_VERSION=$(cargo metadata --no-deps --format-version 1 \
            | jq -r '.packages[0].version')
          if [ "$TAG" != "$CRATE_VERSION" ]; then
            echo "Tag $GITHUB_REF_NAME does not match crate version $CRATE_VERSION"
            exit 1
          fi

      - name: Publish to crates.io
        run: cargo publish
