name: Sync OpenAPI Spec

on:
  schedule:
    - cron: "0 8 * * 1" # Every Monday at UTC 8:00
  workflow_dispatch:
    inputs:
      version:
        description: "Target athena-auth version 0.1.0"
        required: false
        type: string

permissions:
  contents: write
  pull-requests: write

jobs:
  sync-spec:
    name: Sync OpenAPI Spec
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: "20"

      - name: Get current version
        id: current
        run: |
          version=$(node -e "console.log(require('./compat-tests/reference-server/package.json').dependencies['better-auth'])")
          echo "version=$version" >> "$GITHUB_OUTPUT"

      - name: Get target version
        id: target
        run: |
          if [ -n "${{ inputs.version }}" ]; then
            echo "version=${{ inputs.version }}" >> "$GITHUB_OUTPUT"
          else
            version=$(npm view better-auth version)
            echo "version=$version" >> "$GITHUB_OUTPUT"
          fi

      - name: Check if update is needed
        id: check
        run: |
          if [ "${{ steps.current.outputs.version }}" = "${{ steps.target.outputs.version }}" ]; then
            echo "skip=true" >> "$GITHUB_OUTPUT"
            echo "Already at v${{ steps.current.outputs.version }}, nothing to do."
          else
            echo "skip=false" >> "$GITHUB_OUTPUT"
            echo "Updating from v${{ steps.current.outputs.version }} to v${{ steps.target.outputs.version }}"
          fi

      - name: Generate OpenAPI spec
        if: steps.check.outputs.skip == 'false'
        run: |
          TARGET="${{ steps.target.outputs.version }}"
          TMPDIR=$(mktemp -d)

          cd "$TMPDIR"
          npm init -y --silent
          node -e "
            const pkg = JSON.parse(require('fs').readFileSync('package.json','utf8'));
            pkg.type = 'module';
            require('fs').writeFileSync('package.json', JSON.stringify(pkg, null, 2));
          "
          npm install "better-auth@$TARGET" "@better-auth/passkey@$TARGET" js-yaml --silent

          cp "$GITHUB_WORKSPACE/scripts/generate-openapi-matrix.mjs" .
          node generate-openapi-matrix.mjs --profile aligned-rs --output spec.json

          node -e "
            import('js-yaml').then(yaml => {
              const fs = require('fs');
              const spec = JSON.parse(fs.readFileSync('spec.json', 'utf8'));
              fs.writeFileSync(
                '$GITHUB_WORKSPACE/better-auth.yaml',
                yaml.dump(spec, { lineWidth: -1, noRefs: true, sortKeys: false })
              );
              console.log('Wrote better-auth.yaml');
            });
          "

      - name: Update reference-server dependency
        if: steps.check.outputs.skip == 'false'
        working-directory: compat-tests/reference-server
        run: npm install "better-auth@${{ steps.target.outputs.version }}" --save-exact

      - name: Create Pull Request
        if: steps.check.outputs.skip == 'false'
        uses: peter-evans/create-pull-request@v7
        with:
          branch: chore/sync-openapi-v${{ steps.target.outputs.version }}
          commit-message: "chore(spec): sync OpenAPI spec to better-auth v${{ steps.target.outputs.version }}"
          title: "chore(spec): sync OpenAPI spec to better-auth v${{ steps.target.outputs.version }}"
          body: |
            Automated OpenAPI spec sync.

            - **Current version**: v${{ steps.current.outputs.version }}
            - **Target version**: v${{ steps.target.outputs.version }}

            Generated by the `sync-openapi` workflow.
          labels: openapi-sync
