# Example: shorten a URL with LinkBit when a release is published.
# Copy to .github/workflows/ in your repo. Set secret LINKBIT_API_KEY (slk_...).
name: LinkBit — shorten release URL

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      destination:
        description: URL to shorten
        required: true
        type: string
      slug:
        description: Optional custom slug
        required: false
        type: string

jobs:
  shorten:
    runs-on: ubuntu-latest
    steps:
      - name: Shorten URL
        env:
          LINKBIT_API_KEY: ${{ secrets.LINKBIT_API_KEY }}
          LINKBIT_APP_URL: ${{ secrets.LINKBIT_APP_URL }}
          DESTINATION: ${{ github.event_name == 'workflow_dispatch' && inputs.destination || github.event.release.html_url }}
          SLUG: ${{ github.event_name == 'workflow_dispatch' && inputs.slug || '' }}
        run: |
          set -euo pipefail
          if [ -z "${LINKBIT_API_KEY:-}" ]; then
            echo "Missing secret LINKBIT_API_KEY (slk_...)" >&2
            exit 1
          fi
          APP_URL="${LINKBIT_APP_URL:-https://linkbit.live}"
          BODY=$(jq -n \
            --arg destination "$DESTINATION" \
            --arg slug "$SLUG" \
            --arg note "github-actions" \
            --arg utm_source "github" \
            --arg utm_medium "release" \
            '{
              destination: $destination,
              note: $note,
              utm_source: $utm_source,
              utm_medium: $utm_medium
            } + (if $slug != "" then {slug: $slug} else {} end)')
          RESP=$(curl -sS -X POST "${APP_URL}/api/v1/links" \
            -H "x-api-key: ${LINKBIT_API_KEY}" \
            -H "Content-Type: application/json" \
            -d "$BODY")
          echo "$RESP" | jq .
          SHORT=$(echo "$RESP" | jq -r '.shortUrl // empty')
          if [ -z "$SHORT" ]; then
            echo "Shorten failed" >&2
            exit 1
          fi
          echo "Short link: $SHORT"
