#!/bin/bash

# shellcheck shell=bash

# Check branch existence
bridge_check_branch() {
  if [[ -z "${1:-}" ]]; then
    json_error "Branch name required"
    return 1
  fi
  branch_name="$1"

  if git_require_repo_root >/dev/null 2>&1; then
    local_exists="false"
    if git_branch_exists "$branch_name"; then
      local_exists="true"
    fi

    remote_exists="false"
    remote_error=""
    remote_name="origin"
    root="$(git_repo_root)"

    if (cd "$root" && git remote get-url "$remote_name" >/dev/null 2>&1); then
      remote_output="$(cd "$root" && git ls-remote --heads "$remote_name" "$branch_name" 2>&1)"
      remote_status=$?
      if [[ $remote_status -eq 0 ]]; then
        if [[ -n "$remote_output" ]]; then
          remote_exists="true"
        fi
      else
        remote_error="$remote_output"
      fi
    else
      remote_error="Remote '$remote_name' not configured"
    fi

    if [[ -n "$remote_error" ]]; then
      remote_error="$(printf '%s' "$remote_error" | tr '\n' ' ')"
    fi

    local specs=(
      "local_exists:b=$local_exists"
      "remote_exists:b=$remote_exists"
    )
    if [[ -n "$remote_error" ]]; then
      specs+=("remote_error:s=$remote_error")
    fi
    json_object "${specs[@]}"
  else
    json_error "Not a git repository"
  fi
}
