#!/usr/bin/env bash
#
# record-delete.sh — Delete a DNS record from a Cloudflare zone
#
# Usage: record-delete.sh -z <zone> -r <record-id> [-a instance]
#
# Options:
#   -z zone       Zone name or ID (required)
#   -r record-id  DNS record ID (required)
#   -a instance   Cloudflare instance name (default: uses credentials default)
#   -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=""
RECORD_ID=""

while getopts "z:a:r:h" opt; do
  case $opt in
    z) ZONE="$OPTARG" ;;
    a) INSTANCE="$OPTARG" ;;
    r) RECORD_ID="$OPTARG" ;;
    h) head -11 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
    *) echo "Usage: $0 -z <zone> -r <record-id> [-a instance]" >&2; exit 1 ;;
  esac
done

if [[ -z "$ZONE" || -z "$RECORD_ID" ]]; then
  echo "Error: -z and -r are both required" >&2
  exit 1
fi

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

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

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

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

echo "Deleted DNS record $RECORD_ID from zone $ZONE"
