#!/bin/bash
# List GitHub pull requests using gh CLI

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib.sh
source "$SCRIPT_DIR/lib.sh"

# Arguments
STATE="${1:-open}"
BASE="$2"

# Check if gh is installed
if ! command -v gh &> /dev/null; then
    echo "Error: GitHub CLI (gh) is not installed" >&2
    exit 1
fi

# gh is piped into jq below, and a pipeline reports jq's exit status, so a
# failed gh call would leave this script printing nothing and exiting 0. The
# guard catches the common cause, being run outside the repository. Any other
# gh failure is still swallowed by that pipe; see the note in lib.sh.
require_repo_context

# Build command
CMD="gh pr list --state $STATE --json number,title,headRefName,baseRefName,state,updatedAt,author"

# Add base branch filter if specified
if [ -n "$BASE" ]; then
    CMD="$CMD --base $BASE"
fi

# Execute and format
eval "$CMD" | jq '.'
