name: Sync with upstream

on:
  schedule:
    - cron: "0 8 1 * *"
  workflow_dispatch:

jobs:
  sync:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      issues: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Add upstream remote
        run: git remote add upstream https://github.com/9seconds/mtg.git

      - name: Fetch upstream
        run: git fetch upstream

      - name: Check for new commits
        id: check
        run: |
          COUNT=$(git rev-list --count HEAD..upstream/master)
          echo "count=$COUNT" >> "$GITHUB_OUTPUT"
          echo "Upstream is $COUNT commits ahead"

      - name: Merge upstream
        if: steps.check.outputs.count != '0'
        id: merge
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git merge upstream/master --no-edit
        continue-on-error: true

      - name: Push if merge succeeded
        if: steps.check.outputs.count != '0' && steps.merge.outcome == 'success'
        run: git push origin master

      - name: Create issue on conflict
        if: steps.merge.outcome == 'failure'
        uses: actions/github-script@v7
        with:
          script: |
            await github.rest.issues.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: 'Upstream sync failed — merge conflict',
              body: 'Automatic merge from `9seconds/mtg:master` failed due to conflicts.\n\nResolve manually:\n```\ngit fetch upstream\ngit merge upstream/master\n# fix conflicts\ngit push origin master\n```',
              labels: ['sync']
            });
