name: Publish ksef-shared-types

on:
  push:
    branches:
      - "main"
    paths:
      - "Cargo.toml"
      - "Cargo.lock"
      - "src/**"
      - ".github/workflows/publish-ksef-shared-types.yml"
  workflow_dispatch:

permissions:
  contents: read

concurrency:
  group: publish-ksef-shared-types
  cancel-in-progress: false

jobs:
  publish:
    name: Publish crate to crates.io
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: .

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

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

      - name: Verify package is publishable
        run: cargo package --locked

      - name: Publish crate (idempotent)
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        run: |
          set +e
          OUTPUT="$(cargo publish --locked 2>&1)"
          STATUS=$?
          set -e

          echo "${OUTPUT}"

          if [ "${STATUS}" -eq 0 ]; then
            echo "Publish succeeded."
            exit 0
          fi

          if echo "${OUTPUT}" | grep -Eiq "already uploaded|already exists"; then
            echo "Version already exists on crates.io. Treating as success."
            exit 0
          fi

          echo "Publish failed."
          exit "${STATUS}"
