name: CI

on:
  push:
    branches: [ "**" ]
  pull_request:
    branches: [ "**" ]

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build_test_package:
    runs-on: gitea-runner-host
    container:
      image: maven:3.9-eclipse-temurin-17
    steps:
      - name: Show Java and Maven versions
        run: |
          java -version
          mvn -v
      - name: Build and test
        run: mvn -B -DskipTests=false clean verify
      - name: Package
        run: mvn -B -DskipTests clean package

  auto_merge:
    runs-on: gitea-runner-host
    needs: build_test_package
    if: ${{ github.event_name == 'pull_request' && needs.build_test_package.result == 'success' }}
    steps:
      - name: Auto-merge PR on success
        env:
          # Prefer GITEA_TOKEN; fall back to giteatoken if provided
          GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
          GITEA_TOKEN_ALT: ${{ secrets.giteatoken }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
          REPO: ${{ github.repository }}
        run: |
          if [ -z "$GITEA_TOKEN" ] && [ -n "$GITEA_TOKEN_ALT" ]; then
            GITEA_TOKEN="$GITEA_TOKEN_ALT"
          fi
          if [ -z "$GITEA_TOKEN" ]; then
            echo "No token found in secrets (GITEA_TOKEN or giteatoken). Skipping auto-merge."; exit 0;
          fi
          curl -sS -H "Authorization: token $GITEA_TOKEN" -H 'Content-Type: application/json' \
            -X POST "http://localhost:3000/api/v1/repos/${REPO}/pulls/${PR_NUMBER}/merge" \
            -d '{"Do":"squash","delete_branch_after_merge":true}'
