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

# Emergency operator utility to resend form emails by raw form ID.
# Intended for short-term recovery when tokenized pdfDownloadUrl data is unavailable.

usage() {
  cat <<'EOF'
Usage:
  # Single resend
  emergency-resend-email.sh single \
    --base-url https://localhost:8443 \
    --username admin \
    --password 'secret' \
    --form-type bonus \
    --form-id 42

  # Bulk resend from CSV with headers: formType,formId
  emergency-resend-email.sh bulk \
    --base-url https://localhost:8443 \
    --username admin \
    --password 'secret' \
    --csv ./failed-forms.csv

Optional:
  --insecure   Skip TLS certificate verification (curl -k)

Notes:
  - Requires Admin or Office account.
  - Calls POST /api/v1/admin/forms/{formType}/{formId}/resend-email-by-id
EOF
}

require_arg() {
  local name="$1"
  local value="$2"
  if [[ -z "$value" ]]; then
    echo "ERROR: missing required argument $name" >&2
    usage
    exit 1
  fi
}

extract_jwt() {
  local json="$1"

  if command -v jq >/dev/null 2>&1; then
    printf '%s' "$json" | jq -r '.jwt // empty'
    return
  fi

  if command -v python3 >/dev/null 2>&1; then
    python3 - <<'PY' "$json"
import json, sys
try:
    obj = json.loads(sys.argv[1])
    print(obj.get('jwt', ''))
except Exception:
    print('')
PY
    return
  fi

  # Minimal fallback parser
  printf '%s' "$json" | sed -n 's/.*"jwt"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p'
}

mode="${1:-}"
if [[ "$mode" != "single" && "$mode" != "bulk" ]]; then
  usage
  exit 1
fi
shift

BASE_URL="https://localhost:8443"
USERNAME=""
PASSWORD=""
FORM_TYPE=""
FORM_ID=""
CSV_FILE=""
CURL_INSECURE=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --base-url) BASE_URL="$2"; shift 2 ;;
    --username) USERNAME="$2"; shift 2 ;;
    --password) PASSWORD="$2"; shift 2 ;;
    --form-type) FORM_TYPE="$2"; shift 2 ;;
    --form-id) FORM_ID="$2"; shift 2 ;;
    --csv) CSV_FILE="$2"; shift 2 ;;
    --insecure) CURL_INSECURE="-k"; shift 1 ;;
    -h|--help) usage; exit 0 ;;
    *)
      echo "ERROR: unknown argument $1" >&2
      usage
      exit 1
      ;;
  esac
done

require_arg "--base-url" "$BASE_URL"
require_arg "--username" "$USERNAME"
require_arg "--password" "$PASSWORD"

if [[ "$mode" == "single" ]]; then
  require_arg "--form-type" "$FORM_TYPE"
  require_arg "--form-id" "$FORM_ID"
else
  require_arg "--csv" "$CSV_FILE"
  if [[ ! -f "$CSV_FILE" ]]; then
    echo "ERROR: CSV file not found: $CSV_FILE" >&2
    exit 1
  fi
fi

LOGIN_PAYLOAD=$(cat <<JSON
{"username":"$USERNAME","password":"$PASSWORD","rememberMe":false}
JSON
)

echo $LOGIN_PAYLOAD
LOGIN_RESPONSE=$(curl -sS $CURL_INSECURE \
  -H "Content-Type: application/json" \
  -X POST "$BASE_URL/api/v1/auth/login" \
  -d "$LOGIN_PAYLOAD")

JWT=$(extract_jwt "$LOGIN_RESPONSE")
if [[ -z "$JWT" || "$JWT" == "null" ]]; then
  echo "ERROR: login failed or JWT missing" >&2
  echo "$LOGIN_RESPONSE" >&2
  exit 1
fi

call_resend() {
  local form_type="$1"
  local form_id="$2"
  local url="$BASE_URL/api/v1/admin/forms/$form_type/$form_id/resend-email-by-id"

  local http_code
  local body_file
  body_file=$(mktemp)

  http_code=$(curl -sS $CURL_INSECURE \
    -o "$body_file" \
    -w "%{http_code}" \
    -H "Authorization: Bearer $JWT" \
    -H "Content-Type: application/json" \
    -X POST "$url")

  local body
  body=$(cat "$body_file")
  rm -f "$body_file"

  if [[ "$http_code" == "200" ]]; then
    echo "OK,formType=$form_type,formId=$form_id,http=$http_code,response=$body"
  else
    echo "ERROR,formType=$form_type,formId=$form_id,http=$http_code,response=$body"
  fi
}

if [[ "$mode" == "single" ]]; then
  call_resend "$FORM_TYPE" "$FORM_ID"
  exit 0
fi

# Bulk mode: expected CSV headers formType,formId
line_no=0
while IFS=, read -r form_type form_id _rest; do
  line_no=$((line_no + 1))

  # Skip header
  if [[ $line_no -eq 1 && "$form_type" == "formType" ]]; then
    continue
  fi

  # Skip blank lines
  if [[ -z "${form_type// }" && -z "${form_id// }" ]]; then
    continue
  fi

  if [[ -z "${form_type// }" || -z "${form_id// }" ]]; then
    echo "ERROR,line=$line_no,reason=missing formType or formId"
    continue
  fi

  call_resend "$form_type" "$form_id"
done < "$CSV_FILE"


