name: Full Mirror to GitLab

on:
  push:
    branches:
      - "**"
  pull_request:
    types: [opened, reopened, closed, edited]
  issues:
    types: [opened, edited, closed, reopened]

jobs:
  mirror-code:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repo
        uses: actions/checkout@v3

      - name: Setup Git
        run: |
          git config --global user.email "github-actions[bot]@users.noreply.github.com"
          git config --global user.name "github-actions[bot]"

      - name: Fetch GitLab branch
        run: |
          git remote add gitlab https://oauth2:${{ secrets.GITLAB_TOKEN }}@gitlab.com/foxixus/neomovies_mobile.git
          git fetch gitlab main || true

      - name: Check for differences with GitLab
        id: diffcheck
        run: |
          if ! git rev-parse gitlab/main >/dev/null 2>&1; then
            echo "has_diff=true" >> $GITHUB_OUTPUT
          else
            DIFF=$(git rev-list --left-right --count HEAD...gitlab/main | awk '{print $1}')
            if [[ "$DIFF" -gt 0 ]]; then
              echo "has_diff=true" >> $GITHUB_OUTPUT
            else
              echo "has_diff=false" >> $GITHUB_OUTPUT
            fi
          fi

      - name: Push to GitLab if there are changes
        if: steps.diffcheck.outputs.has_diff == 'true'
        run: git push gitlab HEAD:main

  mirror-issues:
    runs-on: ubuntu-latest
    if: github.event_name == 'issues'
    steps:
      - name: Sync issue to GitLab
        run: |
          curl --request POST "https://gitlab.com/api/v4/projects/foxixus%2Fneomovies_mobile/issues" \
            --header "PRIVATE-TOKEN: ${{ secrets.GITLAB_TOKEN }}" \
            --header "Content-Type: application/json" \
            --data "{
              \"title\": \"${{ github.event.issue.title }}\",
              \"description\": \"${{ github.event.issue.body }}\"
            }"

  mirror-prs:
    runs-on: ubuntu-latest
    if: github.event_name == 'pull_request'
    steps:
      - name: Sync PR to GitLab MR
        run: |
          curl --request POST "https://gitlab.com/api/v4/projects/foxixus%2Fneomovies_mobile/merge_requests" \
            --header "PRIVATE-TOKEN: ${{ secrets.GITLAB_TOKEN }}" \
            --header "Content-Type: application/json" \
            --data "{
              \"title\": \"${{ github.event.pull_request.title }}\",
              \"source_branch\": \"${{ github.event.pull_request.head.ref }}\",
              \"target_branch\": \"${{ github.event.pull_request.base.ref }}\",
              \"description\": \"${{ github.event.pull_request.body }}\"
            }"