#!/bin/bash
# pr-merge.sh - Merge pull requests on Gitea or GitHub
# Usage: pr-merge.sh -n PR_NUMBER [-m method] [-d]

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/detect-platform.sh"

# Default values
PR_NUMBER=""
MERGE_METHOD="merge"  # merge, squash, rebase
DELETE_BRANCH=false

usage() {
    cat <<EOF
Usage: $(basename "$0") [OPTIONS]

Merge a pull request on the current repository (Gitea or GitHub).

Options:
    -n, --number NUMBER     PR number to merge (required)
    -m, --method METHOD     Merge method: merge, squash, rebase (default: merge)
    -d, --delete-branch     Delete the head branch after merge
    -h, --help              Show this help message

Examples:
    $(basename "$0") -n 42                    # Merge PR #42
    $(basename "$0") -n 42 -m squash          # Squash merge
    $(basename "$0") -n 42 -m rebase -d       # Rebase and delete branch
EOF
    exit 1
}

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -n|--number)
            PR_NUMBER="$2"
            shift 2
            ;;
        -m|--method)
            MERGE_METHOD="$2"
            shift 2
            ;;
        -d|--delete-branch)
            DELETE_BRANCH=true
            shift
            ;;
        -h|--help)
            usage
            ;;
        *)
            echo "Unknown option: $1" >&2
            usage
            ;;
    esac
done

if [[ -z "$PR_NUMBER" ]]; then
    echo "Error: PR number is required (-n)" >&2
    usage
fi

PLATFORM=$(detect_platform)

case "$PLATFORM" in
    github)
        CMD="gh pr merge $PR_NUMBER"
        case "$MERGE_METHOD" in
            merge)   CMD="$CMD --merge" ;;
            squash)  CMD="$CMD --squash" ;;
            rebase)  CMD="$CMD --rebase" ;;
            *)
                echo "Error: Invalid merge method '$MERGE_METHOD'" >&2
                exit 1
                ;;
        esac
        [[ "$DELETE_BRANCH" == true ]] && CMD="$CMD --delete-branch"
        eval "$CMD"
        ;;
    gitea)
        # tea pr merge syntax
        CMD="tea pr merge $PR_NUMBER"

        # tea merge style flags
        case "$MERGE_METHOD" in
            merge)   CMD="$CMD --style merge" ;;
            squash)  CMD="$CMD --style squash" ;;
            rebase)  CMD="$CMD --style rebase" ;;
            *)
                echo "Error: Invalid merge method '$MERGE_METHOD'" >&2
                exit 1
                ;;
        esac

        # Delete branch after merge if requested
        if [[ "$DELETE_BRANCH" == true ]]; then
            echo "Note: Branch deletion after merge may need to be done separately with tea" >&2
        fi

        eval "$CMD"
        ;;
    *)
        echo "Error: Could not detect git platform" >&2
        exit 1
        ;;
esac

echo "PR #$PR_NUMBER merged successfully"
