#!/usr/bin/env bash
set -euo pipefail

HORIZON_API_BASE="${HORIZON_API_BASE:-https://billing.myhorizon.co.za}"
HORIZON_API_KEY="${HORIZON_API_KEY:-}"

usage() {
  cat <<'HELP'
hmail — Horizon Mail CLI

Usage:
  hmail auth.md
  hmail provision [mailbox-prefix]
  hmail claim-nonce <client-id> <claim-token>
  hmail send --to <email> --subject <subject> --text <body>

Environment:
  HORIZON_API_BASE  Default: https://billing.myhorizon.co.za
  HORIZON_API_KEY   Required for authenticated commands like send
HELP
}

json_escape() {
  python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))'
}

case "${1:-}" in
  auth.md)
    curl -fsSL "$HORIZON_API_BASE/auth.md"
    ;;
  provision)
    prefix="${2:-}"
    if [[ -n "$prefix" ]]; then
      curl -fsSL -X POST "$HORIZON_API_BASE/api/auth/agent/provision" \
        -H 'content-type: application/json' \
        -d "{\"mailboxPrefix\":\"$prefix\"}"
    else
      curl -fsSL -X POST "$HORIZON_API_BASE/api/auth/agent/provision" \
        -H 'content-type: application/json' \
        -d '{}'
    fi
    ;;
  claim-nonce)
    [[ $# -eq 3 ]] || { usage >&2; exit 64; }
    curl -fsSL -X POST "$HORIZON_API_BASE/api/auth/agent/claim-nonces" \
      -H 'content-type: application/json' \
      -d "{\"client_id\":\"$2\",\"claim_token\":\"$3\"}"
    ;;
  send)
    [[ -n "$HORIZON_API_KEY" ]] || { echo 'HORIZON_API_KEY is required' >&2; exit 64; }
    shift
    to=""; subject=""; text=""
    while [[ $# -gt 0 ]]; do
      case "$1" in
        --to) to="$2"; shift 2 ;;
        --subject) subject="$2"; shift 2 ;;
        --text) text="$2"; shift 2 ;;
        *) usage >&2; exit 64 ;;
      esac
    done
    [[ -n "$to" && -n "$subject" && -n "$text" ]] || { usage >&2; exit 64; }
    to_json=$(printf %s "$to" | json_escape)
    subject_json=$(printf %s "$subject" | json_escape)
    text_json=$(printf %s "$text" | json_escape)
    curl -fsSL -X POST "$HORIZON_API_BASE/api/outbound" \
      -H "authorization: Bearer $HORIZON_API_KEY" \
      -H 'content-type: application/json' \
      -d "{\"to\":$to_json,\"subject\":$subject_json,\"text\":$text_json}"
    ;;
  -h|--help|help|"")
    usage
    ;;
  *)
    usage >&2
    exit 64
    ;;
esac
