#!/bin/bash
# Provision 11 matched VWP extensions with correct M365 emails
# Domain: vwp.91912.service
# E911 Address: a-6a395c03d4cfe

DOMAIN="vwp.91912.service"
E911="a-6a395c03d4cfe"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PY_WRAPPER="bash $SCRIPT_DIR/../../../.claude/scripts/py.sh"

# Matched users: extension|first_name|last_name|email
USERS=(
  "102|Jesse|Guerrero|jesse@valleywideplastering.com"
  "103|Rose|Guerrero|rose@valleywideplastering.com"
  "104|Shelly|Dooley|shelly@valleywideplastering.com"
  "105|JR|Guerrero|j-r@valleywideplastering.com"
  "107|Payroll|Department|payroll@valleywideplastering.com"
  "109|Kayla|Guerrero|kayla@valleywideplastering.com"
  "110|Ron|Winger|ron@valleywideplastering.com"
  "113|Chris|Guerrero|chris@valleywideplastering.com"
  "114|Ty|Fetters|Ty@CASARICA.NET"
  "115|Toni|Billing|billing@valleywideplastering.onmicrosoft.com"
  "116|Bart|Graffin|estimating@valleywideplastering.com"
)

echo "[INFO] Creating 11 matched VWP users in PacketDial..."
echo ""

SUCCESS=0
FAILED=0

for user_data in "${USERS[@]}"; do
  IFS='|' read -r ext first last email <<< "$user_data"

  echo "[INFO] Creating extension $ext: $first $last ($email)"

  # Build JSON body (name-last-name is required)
  BODY="{\"user\":\"$ext\",\"name-first-name\":\"$first\",\"name-last-name\":\"$last\",\"email\":\"$email\",\"emergency-address-id\":\"$E911\"}"

  # Create user
  RESULT=$($PY_WRAPPER "$SCRIPT_DIR/ns.py" create-user "$DOMAIN" --body "$BODY" --confirm 2>&1)

  if echo "$RESULT" | grep -q "HTTP 400.*already exists"; then
    echo "  [SKIP] Extension $ext already exists"
    ((SUCCESS++))
  elif echo "$RESULT" | grep -qE "HTTP [45]"; then
    echo "  [ERROR] Failed to create extension $ext: $RESULT"
    ((FAILED++))
  else
    echo "  [OK] Created extension $ext"
    ((SUCCESS++))
  fi

  # Small delay to avoid rate limiting
  sleep 1
done

echo ""
echo "[SUMMARY] Users: $SUCCESS created/existing, $FAILED failed"
echo "[INFO] Waiting 30 seconds for async processing..."
sleep 30

echo ""
echo "[INFO] Verifying user creation..."
ACTUAL=$($PY_WRAPPER "$SCRIPT_DIR/ns.py" users "$DOMAIN" 2>/dev/null | grep -c '"user"')
echo "[INFO] PacketDial reports $ACTUAL users total"
