#!/usr/bin/env bash
# Smoke test métier TicketGate — simule maj-wp + workflows admin
# Usage: bash server/scripts/smoke-business.sh [BASE_URL] [API_KEY]
set -euo pipefail

BASE="${1:-http://127.0.0.1:3847}"
API_KEY="${2:-dev-maj-wp-api-key-change-in-prod}"
ADMIN_USER="${ADMIN_USER:-admin}"
ADMIN_PASS="${ADMIN_PASS:-admin}"
COOKIE_JAR=$(mktemp)
trap 'rm -f "$COOKIE_JAR"' EXIT

hr() { echo; echo "══════════════════════════════════════════════════════════"; echo " $1"; echo "══════════════════════════════════════════════════════════"; }
req() { echo ">>> $1 $2"; curl -sS -w "\nHTTP %{http_code}\n" "$@"; echo; }

hr "0. Health"
req GET "$BASE/api/health"

hr "1. Admin login"
req POST "$BASE/api/auth/login" \
  -H 'Content-Type: application/json' \
  -c "$COOKIE_JAR" \
  -d "{\"username\":\"$ADMIN_USER\",\"password\":\"$ADMIN_PASS\"}"

hr "2. Ingest Gmail (simulé via demo ingest)"
GMAIL_RESP=$(curl -sS -X POST "$BASE/api/demo/ingest" \
  -H 'Content-Type: application/json' \
  -b "$COOKIE_JAR" \
  -d '{
    "source_type":"gmail",
    "source_external_id":"gmail-msg-smoke-001",
    "source_url":"https://mail.google.com/mail/u/0/#inbox/smoke001",
    "sender_email":"smoke.test@example.com",
    "sender_name":"Smoke Test",
    "title":"Email smoke test paiement",
    "body":"Contenu email de test smoke.",
    "attachments":[{"filename":"facture.pdf","mimeType":"application/pdf","size":12345,"sourceRef":"att-smoke-1"}]
  }')
echo "$GMAIL_RESP"
GMAIL_ID=$(echo "$GMAIL_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['item']['id'])" 2>/dev/null || true)
echo "GMAIL_ID=$GMAIL_ID"

hr "3. Dédup Gmail — second ingest même messageId"
req POST "$BASE/api/demo/ingest" \
  -H 'Content-Type: application/json' \
  -b "$COOKIE_JAR" \
  -d '{"source_type":"gmail","source_external_id":"gmail-msg-smoke-001","title":"dup","sender_email":"smoke.test@example.com"}'

hr "4. Ingest Monday Chrome (simulé)"
MONDAY_RESP=$(curl -sS -X POST "$BASE/api/demo/ingest" \
  -H 'Content-Type: application/json' \
  -b "$COOKIE_JAR" \
  -d '{
    "source_type":"monday_chrome",
    "source_account":"123",
    "source_external_id":"monday-123-456789",
    "source_url":"https://foo.monday.com/boards/123/pulses/456789",
    "sender_name":"Marie Monday",
    "title":"Item Monday smoke",
    "body":"Description item Monday"
  }')
echo "$MONDAY_RESP"
MONDAY_ID=$(echo "$MONDAY_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['item']['id'])" 2>/dev/null || true)

hr "5. Dédup Monday Chrome"
req POST "$BASE/api/demo/ingest" \
  -H 'Content-Type: application/json' \
  -b "$COOKIE_JAR" \
  -d '{"source_type":"monday_chrome","source_account":"123","source_external_id":"monday-123-456789","title":"dup monday"}'

hr "6. Dédup Monday API vs Chrome (même clé monday-board-item)"
req POST "$BASE/api/demo/ingest" \
  -H 'Content-Type: application/json' \
  -b "$COOKIE_JAR" \
  -d '{"source_type":"monday_api","source_account":"123","source_external_id":"monday-123-456789","title":"from api"}'

hr "7. Pending list"
req GET "$BASE/api/intake/pending" -b "$COOKIE_JAR"

hr "8. Approve Gmail item"
if [[ -n "${GMAIL_ID:-}" ]]; then
  req POST "$BASE/api/intake/$GMAIL_ID/approve" -b "$COOKIE_JAR"
fi

hr "9. Ignore Monday item"
if [[ -n "${MONDAY_ID:-}" ]]; then
  req POST "$BASE/api/intake/$MONDAY_ID/ignore" -b "$COOKIE_JAR"
fi

hr "10. Ignored list + restore Monday"
req GET "$BASE/api/intake/ignored" -b "$COOKIE_JAR"
if [[ -n "${MONDAY_ID:-}" ]]; then
  req POST "$BASE/api/intake/$MONDAY_ID/restore" -b "$COOKIE_JAR"
fi

hr "11. Blacklist sender from Gmail item"
if [[ -n "${GMAIL_ID:-}" ]]; then
  # Re-ingest fresh gmail for blacklist test
  BL_RESP=$(curl -sS -X POST "$BASE/api/demo/ingest" -H 'Content-Type: application/json' -b "$COOKIE_JAR" \
    -d '{"source_type":"gmail","source_external_id":"gmail-bl-test","sender_email":"blacklist.me@example.com","sender_name":"BL Test","title":"BL test"}')
  BL_ID=$(echo "$BL_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['item']['id'])")
  req POST "$BASE/api/intake/$BL_ID/ignore" -b "$COOKIE_JAR"
  req POST "$BASE/api/intake/$BL_ID/blacklist-sender" -b "$COOKIE_JAR"
  hr "11b. New email from blacklisted sender → auto_ignored"
  req POST "$BASE/api/demo/ingest" -H 'Content-Type: application/json' -b "$COOKIE_JAR" \
    -d '{"source_type":"gmail","source_external_id":"gmail-bl-test-2","sender_email":"blacklist.me@example.com","title":"Should auto ignore"}'
  req GET "$BASE/api/intake/ignored" -b "$COOKIE_JAR"
  hr "11c. Deactivate blacklist"
  BL_LIST=$(curl -sS "$BASE/api/blacklist" -b "$COOKIE_JAR")
  BL_SENDER_ID=$(echo "$BL_LIST" | python3 -c "import sys,json; d=json.load(sys.stdin); print(next(x['id'] for x in d if x['sender_key']=='blacklist.me@example.com'))")
  req POST "$BASE/api/blacklist/$BL_SENDER_ID/deactivate" -b "$COOKIE_JAR"
fi

hr "12. maj-wp: GET /api/v1/tickets/ready"
req GET "$BASE/api/v1/tickets/ready" -H "Authorization: Bearer $API_KEY"

hr "13. maj-wp: claim-next"
CLAIM_RESP=$(curl -sS -w "\nHTTP %{http_code}\n" -X POST "$BASE/api/v1/intake/claim-next" \
  -H "Authorization: Bearer $API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"consumer_id":"smoke-maj-wp"}')
echo "$CLAIM_RESP"
CLAIM_ID=$(echo "$CLAIM_RESP" | python3 -c "import sys,json,re; t=sys.stdin.read(); j=json.loads(re.search(r'\{.*\}',t,re.S).group()); print(j['item']['id'])" 2>/dev/null || true)
CLAIM_TOKEN=$(echo "$CLAIM_RESP" | python3 -c "import sys,json,re; t=sys.stdin.read(); j=json.loads(re.search(r'\{.*\}',t,re.S).group()); print(j.get('claim_token',''))" 2>/dev/null || true)

hr "14. maj-wp: second claim concurrent → 409"
if [[ -n "${CLAIM_ID:-}" ]]; then
  req POST "$BASE/api/v1/intake/$CLAIM_ID/claim" \
    -H "Authorization: Bearer $API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{"consumer_id":"smoke-maj-wp-2"}'
fi

hr "15. maj-wp: POST created"
if [[ -n "${CLAIM_ID:-}" ]]; then
  req POST "$BASE/api/v1/intake/$CLAIM_ID/created" \
    -H "Authorization: Bearer $API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{\"claim_token\":\"$CLAIM_TOKEN\",\"maj_wp_ticket_id\":\"WP-SMOKE-42\",\"remote_status\":\"open\",\"remote_message\":\"Ticket créé smoke test\"}"
fi

hr "16. maj-wp: idempotent double created"
if [[ -n "${CLAIM_ID:-}" ]]; then
  req POST "$BASE/api/v1/intake/$CLAIM_ID/created" \
    -H "Authorization: Bearer $API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{"maj_wp_ticket_id":"WP-SMOKE-42","remote_status":"open"}'
fi

hr "17. maj-wp: status update (WAITING_HUMAN message)"
if [[ -n "${CLAIM_ID:-}" ]]; then
  req POST "$BASE/api/v1/intake/$CLAIM_ID/status" \
    -H "Authorization: Bearer $API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{"status":"in_progress","remote_status":"WAITING_HUMAN","remote_message":"WAITING_HUMAN — Informations client manquantes"}'
fi

hr "18. maj-wp: error status"
if [[ -n "${CLAIM_ID:-}" ]]; then
  req POST "$BASE/api/v1/intake/$CLAIM_ID/status" \
    -H "Authorization: Bearer $API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{"status":"failed","remote_status":"error","remote_message":"Échec création","error":"Timeout API prestashop"}'
fi

hr "19. Tickets list (admin UI data)"
req GET "$BASE/api/intake/tickets" -b "$COOKIE_JAR"

hr "20. Extension pairing flow"
PAIR=$(curl -sS -X POST "$BASE/api/extension/pairing" -b "$COOKIE_JAR")
echo "$PAIR"
PAIR_CODE=$(echo "$PAIR" | python3 -c "import sys,json; print(json.load(sys.stdin)['code'])")
req POST "$BASE/api/extension/pair" \
  -H 'Content-Type: application/json' \
  -d "{\"code\":\"$PAIR_CODE\",\"label\":\"smoke-test\"}"

echo
echo "SMOKE BUSINESS COMPLETE"
