name: Upstream Sync and PR

on:
  schedule:
    - cron: '0 0 * * *'
  workflow_dispatch:

jobs:
  sync:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Local Repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Configure Git
        run: |
          git config --global user.name "mizuki"
          git config --global user.email "akiyama@mizuki.guru"

      - name: Add Upstream and Fetch
        run: |
          git remote add upstream https://github.com/cinnyapp/cinny.git
          git fetch upstream dev

      - name: Merge Upstream and Check Changes
        id: check_changes
        run: |
          BRANCH_NAME="upstream-sync-$(date +'%Y%m%d%H%M')"
          git checkout -b $BRANCH_NAME origin/dev
          
          git merge upstream/dev --no-edit --allow-unrelated-histories
          
          if ! git diff --quiet origin/dev HEAD; then
            echo "New upstream changes merged successfully."
            echo "branch_name=$BRANCH_NAME" >> $GITHUB_OUTPUT
            echo "has_changes=true" >> $GITHUB_OUTPUT
            
            git push origin $BRANCH_NAME
          else
            echo "No new upstream changes to apply. Everything is up to date."
            echo "has_changes=false" >> $GITHUB_OUTPUT
          fi

      - name: Create Pull Request via Forgejo API
        if: ${{ steps.check_changes.outputs.has_changes == 'true' }}
        run: |      
          PR_TITLE="chore(deps): sync upstream changes ($(date +'%Y-%m-%d'))"
          PR_BODY="Upstream (cinnyapp/cinny)에 새로운 변경사항이 감지되어 내 커스텀 브랜치(dev)에 병합한 후 생성된 PR입니다."
          HEAD_BRANCH="${{ steps.check_changes.outputs.branch_name }}"
          BASE_BRANCH="dev"
          
          curl -X 'POST' \
            "${{ github.server_url }}/api/v1/repos/${{ github.repository }}/pulls" \
            -H "accept: application/json" \
            -H "Authorization: token ${{ secrets.TOKEN_FORGEJO }}" \
            -H "Content-Type: application/json" \
            -d "{
              \"base\": \"$BASE_BRANCH\",
              \"head\": \"$HEAD_BRANCH\",
              \"title\": \"$PR_TITLE\",
              \"body\": \"$PR_BODY\"
            }"