name: Check DB migration conflict
on:
  push:
    paths:
      - "superset/migrations/**"
    branches:
      - "master"
      - "[0-9].[0-9]*"
  pull_request:
    paths:
      - "superset/migrations/**"
    types: [synchronize, opened, reopened, ready_for_review]

# cancel previous workflow jobs for PRs
concurrency:
  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
  cancel-in-progress: true

jobs:
  check_db_migration_conflict:
    name: Check DB migration conflict
    runs-on: ubuntu-22.04
    permissions:
      contents: read
      pull-requests: write
    steps:
      - name: "Checkout ${{ github.ref }} ( ${{ github.sha }} )"
        uses: actions/checkout@v4
      - name: Check and notify
        uses: actions/github-script@v7
        with:
          github-token: ${{ github.token }}
          script: |
            // API reference: https://octokit.github.io/rest.js
            const currentBranch = context.ref.replace('refs/heads/', '');

            // Find all pull requests to current branch
            const opts = github.rest.pulls.list.endpoint.merge({
              owner: context.repo.owner,
              repo: context.repo.repo,
              base: context.ref,
              state: 'open',
              sort: 'updated',
              per_page: 100,
            });
            const pulls = await github.paginate(opts);
            if (pulls.length > 0) {
              console.log(`Found ${pulls.length} open PRs for base branch "${currentBranch}"`)
            }

            for (const pull of pulls) {
              const listFilesOpts = await github.rest.pulls.listFiles.endpoint.merge({
                owner: context.repo.owner,
                repo: context.repo.repo,
                pull_number: pull.number,
              });
              const files = await github.paginate(listFilesOpts);
              if (
                files.some(x => x.contents_url.includes('/contents/superset/migrations'))
              ) {
                console.log(`PR #${pull.number} "${pull.title}" also added db migration`)
                await github.rest.issues.createComment({
                  issue_number: context.issue.number,
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  issue_number: pull.number,
                  body:
                    `# 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️` +
                    `❗ @${pull.user.login} Your base branch \`${currentBranch}\` has ` +
                    'also updated `superset/migrations`.\n' +
                    '\n' +
                    '**Please consider rebasing your branch and [resolving potential db migration conflicts](https://github.com/apache/superset/blob/master/CONTRIBUTING.md#merging-db-migrations).**',
                });
              }
            }
