name: Promote Beta to Stable

on:
  workflow_dispatch: {}

permissions: {}

jobs:
  promote:
    if: github.repository_owner == 'better-auth' && github.ref == 'refs/heads/next'
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
    steps:
      - name: Generate App Token
        id: app-token
        uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859 # v3.0.0
        if: vars.RELEASE_APP_ID != ''
        with:
          app-id: ${{ vars.RELEASE_APP_ID }}
          private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}

      - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
        with:
          ref: next
          persist-credentials: false
          token: ${{ steps.app-token.outputs.token || secrets.GITHUB_TOKEN }}

      - uses: pnpm/action-setup@41ff72655975bd51cab0327fa583b6e92b6d3061 # v4.2.0

      - uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0
        with:
          node-version-file: '.nvmrc'
          cache: pnpm

      - run: pnpm install --frozen-lockfile

      - name: Exit pre-release and version
        env:
          GITHUB_TOKEN: ${{ steps.app-token.outputs.token || secrets.GITHUB_TOKEN }}
        run: |
          if [ -f .changeset/pre.json ]; then
            pnpm changeset pre exit
          else
            echo "Already out of pre-release mode (retrying previous run?)"
          fi
          pnpm ci:version

      - name: Read version
        id: version
        run: |
          VERSION=$(node -e "console.log(require('./packages/better-auth/package.json').version.replace(/[^0-9.]/g, ''))")
          echo "version=$VERSION" >> "$GITHUB_OUTPUT"
          echo "Promoting to v$VERSION"

      - name: Commit and push
        env:
          GH_TOKEN: ${{ steps.app-token.outputs.token || secrets.GITHUB_TOKEN }}
          VERSION: ${{ steps.version.outputs.version }}
        run: |
          git config user.name "better-release[bot]"
          git config user.email "273320539+better-release[bot]@users.noreply.github.com"
          git remote set-url origin "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git"
          git add -A
          if git diff --cached --quiet; then
            echo "No changes to commit (previous run already pushed)"
          else
            git commit -m "chore: exit pre-release mode for v${VERSION}"
            git push origin next || { echo "::error::Push to next failed. Check branch protection rules."; exit 1; }
          fi

      - name: Create promote PR
        env:
          GH_TOKEN: ${{ steps.app-token.outputs.token || secrets.GITHUB_TOKEN }}
          VERSION: ${{ steps.version.outputs.version }}
        run: |
          EXISTING=$(gh pr list --base main --head next --state open --repo "$GITHUB_REPOSITORY" --json number --jq '.[0].number // empty')
          if [ -n "$EXISTING" ]; then
            echo "Promote PR #$EXISTING already exists"
          else
            gh pr create \
              --base main \
              --head next \
              --title "chore: promote v${VERSION} to stable" \
              --body "Promotes v${VERSION} from beta to stable. Merging this PR publishes all packages to npm with the \`latest\` tag.\n\n**This PR must be merged by an admin using 'Create a merge commit'** (not squash, not rebase). The admin bypass is required because main enforces linear history for regular PRs, but the promotion needs a merge commit to preserve individual contributor commits and their verified signatures."
          fi

      - name: Summary
        env:
          VERSION: ${{ steps.version.outputs.version }}
        run: |
          {
            echo "### Beta promoted"
            echo ""
            echo "- **Version:** \`$VERSION\`"
            echo "- **Action:** Review and merge the PR with **Create a merge commit** (admin bypass)."
            echo ""
            echo "### After promotion"
            echo "Once the promote PR is merged and the sync PR (main to next) is merged:"
            echo '```'
            echo "pnpm changeset pre enter beta && git add .changeset/pre.json && git commit -m 'chore: re-enter beta pre-release mode' && git push origin next"
            echo '```'
          } >> "$GITHUB_STEP_SUMMARY"
