#!/bin/bash
set -euo pipefail

usage() {
  cat <<'EOF'
Usage:
  query-changefeed-mapping.sh <cluster_id> [cluster_type] [env]

Arguments:
  cluster_id    TiDB cluster ID.
  cluster_type  DEDICATED_TIDB (default), SHARED_POOL, or LOGICAL_CLUSTER.
  env           prod (default), staging, or dev.

Authentication:
  Set DEVOPS_API_TOKEN or put it in .env.
EOF
}

main() {
  local cluster_id="${1:-}"
  local cluster_type="${2:-DEDICATED_TIDB}"
  local devops_env="${3:-prod}"
  local script_dir
  local devops_http

  if [[ -z "${cluster_id}" ]]; then
    usage >&2
    exit 2
  fi

  case "${cluster_type}" in
    DEDICATED_TIDB|SHARED_POOL|LOGICAL_CLUSTER) ;;
    *)
      printf 'unsupported cluster_type: %s\n' "${cluster_type}" >&2
      exit 2
      ;;
  esac

  case "${devops_env}" in
    prod|staging|dev) ;;
    *)
      printf 'unsupported env: %s\n' "${devops_env}" >&2
      exit 2
      ;;
  esac

  if ! command -v jq >/dev/null 2>&1; then
    printf 'jq is required\n' >&2
    exit 1
  fi

  script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  devops_http="${script_dir}/../../scripts/devops_http.sh"

  "${devops_http}" \
    --env "${devops_env}" \
    --path "/ticdc-meta/${cluster_type}/internal-changefeeds/${cluster_id}" |
    jq -e '
      if (.changefeeds | type) != "array" then
        error("response does not contain a changefeeds array")
      else
        [.changefeeds[] | {
          changefeed_name: .display_name,
          changefeed_id: .display_id,
          internal_id: .id,
          status: .status,
          destination: .downstream_type,
          ticdc_cluster_id: .ticdc_cluster.id,
          ticdc_cluster_name: .ticdc_cluster.name
        }]
      end
    '
}

main "$@"
