#!/usr/bin/env bash
#
# record-list.sh — List DNS records for a Cloudflare zone
#
# Usage: record-list.sh -z <zone> [-a instance] [-t type] [-n name] [-f format]
#
# Options:
#   -z zone       Zone name or ID (required)
#   -a instance   Cloudflare instance name (default: uses credentials default)
#   -t type       Filter by record type (A, AAAA, CNAME, MX, TXT, etc.)
#   -n name       Filter by record name
#   -f format     Output format: table (default), json
#   -h            Show this help
set -euo pipefail

MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
source "$(dirname "$0")/_lib.sh"

ZONE=""
INSTANCE=""
TYPE=""
NAME=""
FORMAT="table"

while getopts "z:a:t:n:f:h" opt; do
  case $opt in
    z) ZONE="$OPTARG" ;;
    a) INSTANCE="$OPTARG" ;;
    t) TYPE="$OPTARG" ;;
    n) NAME="$OPTARG" ;;
    f) FORMAT="$OPTARG" ;;
    h) head -14 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
    *) echo "Usage: $0 -z <zone> [-a instance] [-t type] [-n name] [-f format]" >&2; exit 1 ;;
  esac
done

if [[ -z "$ZONE" ]]; then
  echo "Error: -z zone is required" >&2
  exit 1
fi

cf_load_instance "$INSTANCE"
ZONE_ID=$(cf_resolve_zone "$ZONE") || exit 1

# Build query params
params="per_page=100"
[[ -n "$TYPE" ]] && params="${params}&type=${TYPE}"
[[ -n "$NAME" ]] && params="${params}&name=${NAME}"

response=$(curl -s -w "\n%{http_code}" \
  -H "Authorization: $(cf_auth)" \
  -H "Content-Type: application/json" \
  "${CF_API}/zones/${ZONE_ID}/dns_records?${params}")

http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')

if [[ "$http_code" != "200" ]]; then
  echo "Error: Failed to list records (HTTP $http_code)" >&2
  echo "$body" | jq -r '.errors[]?.message // empty' 2>/dev/null >&2
  exit 1
fi

if [[ "$FORMAT" == "json" ]]; then
  echo "$body" | jq '.result'
  exit 0
fi

echo "RECORD ID                         TYPE   NAME                                    CONTENT                          PROXIED  TTL"
echo "--------------------------------  -----  --------------------------------------  -------------------------------  -------  -----"
echo "$body" | jq -r '.result[] | [
  .id,
  .type,
  .name,
  .content,
  (if .proxied then "yes" else "no" end),
  (if .ttl == 1 then "auto" else (.ttl | tostring) end)
] | @tsv' | while IFS=$'\t' read -r id type name content proxied ttl; do
  printf "%-32s  %-5s  %-38s  %-31s  %-7s  %s\n" "$id" "$type" "${name:0:38}" "${content:0:31}" "$proxied" "$ttl"
done
