#!/usr/bin/env bash
#
# record-create.sh — Create a DNS record in a Cloudflare zone
#
# Usage: record-create.sh -z <zone> -t <type> -n <name> -c <content> [-a instance] [-l ttl] [-p] [-P priority]
#
# Options:
#   -z zone       Zone name or ID (required)
#   -t type       Record type: A, AAAA, CNAME, MX, TXT, etc. (required)
#   -n name       Record name, e.g. "app" or "app.example.com" (required)
#   -c content    Record value/content (required)
#   -a instance   Cloudflare instance name (default: uses credentials default)
#   -l ttl        TTL in seconds (default: 1 = auto)
#   -p            Enable Cloudflare proxy (orange cloud)
#   -P priority   MX/SRV priority (default: 10)
#   -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=""
CONTENT=""
TTL=1
PROXIED=false
PRIORITY=""

while getopts "z:a:t:n:c:l:pP:h" opt; do
  case $opt in
    z) ZONE="$OPTARG" ;;
    a) INSTANCE="$OPTARG" ;;
    t) TYPE="$OPTARG" ;;
    n) NAME="$OPTARG" ;;
    c) CONTENT="$OPTARG" ;;
    l) TTL="$OPTARG" ;;
    p) PROXIED=true ;;
    P) PRIORITY="$OPTARG" ;;
    h) head -18 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
    *) echo "Usage: $0 -z <zone> -t <type> -n <name> -c <content> [-a instance] [-l ttl] [-p] [-P priority]" >&2; exit 1 ;;
  esac
done

if [[ -z "$ZONE" || -z "$TYPE" || -z "$NAME" || -z "$CONTENT" ]]; then
  echo "Error: -z, -t, -n, and -c are all required" >&2
  exit 1
fi

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

# Build JSON payload
payload=$(jq -n \
  --arg type "$TYPE" \
  --arg name "$NAME" \
  --arg content "$CONTENT" \
  --argjson ttl "$TTL" \
  --argjson proxied "$PROXIED" \
  '{type: $type, name: $name, content: $content, ttl: $ttl, proxied: $proxied}')

# Add priority for MX/SRV records
if [[ -n "$PRIORITY" ]]; then
  payload=$(echo "$payload" | jq --argjson priority "$PRIORITY" '. + {priority: $priority}')
fi

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

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

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

record_id=$(echo "$body" | jq -r '.result.id')
echo "Created $TYPE record: $NAME → $CONTENT (ID: $record_id)"
