name: Update NPM Dist Tag

on:
  workflow_dispatch:
    inputs:
      version:
        description: 'Version to tag (e.g., 1.2.5)'
        required: true
        type: string
      tag:
        description: 'Dist tag to update (e.g., latest, beta)'
        required: true
        type: choice
        options:
          - latest
          - beta
          - next
          - canary

permissions:
  contents: read
  id-token: write

jobs:
  update-tag:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Use Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          registry-url: https://registry.npmjs.org
          always-auth: true

      - name: Validate version exists
        run: |
          set -euo pipefail
          VERSION="${{ github.event.inputs.version }}"
          TAG="${{ github.event.inputs.tag }}"

          echo "Checking if version $VERSION exists on npm..."
          if ! npm view opencode-antigravity-auth@$VERSION version >/dev/null 2>&1; then
            echo "ERROR: Version $VERSION does not exist on npm" >&2
            echo "Available versions:" >&2
            npm view opencode-antigravity-auth versions --json | tail -20 >&2
            exit 1
          fi

          echo "Version $VERSION exists on npm"
          echo "Current dist-tags:"
          npm dist-tag ls opencode-antigravity-auth

      - name: Update dist-tag
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: |
          set -euo pipefail
          VERSION="${{ github.event.inputs.version }}"
          TAG="${{ github.event.inputs.tag }}"

          echo "Updating @$TAG tag to version $VERSION..."
          npm dist-tag add opencode-antigravity-auth@$VERSION $TAG

          echo ""
          echo "Updated dist-tags:"
          npm dist-tag ls opencode-antigravity-auth

      - name: Summary
        run: |
          echo "## NPM Dist Tag Updated! 🏷️" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "**Version:** ${{ github.event.inputs.version }}" >> $GITHUB_STEP_SUMMARY
          echo "**Tag:** @${{ github.event.inputs.tag }}" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "Users can now install with:" >> $GITHUB_STEP_SUMMARY
          echo '```bash' >> $GITHUB_STEP_SUMMARY
          echo "npm install opencode-antigravity-auth@${{ github.event.inputs.tag }}" >> $GITHUB_STEP_SUMMARY
          echo '```' >> $GITHUB_STEP_SUMMARY
