#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR/.."

BASE_URL="${BASE_URL:-http://localhost/msg-platform}"
CHANNEL_URL="${CHANNEL_URL:-http://localhost:8000}"

command -v curl >/dev/null 2>&1 || { echo "curl is required but not installed."; exit 1; }
command -v jq >/dev/null 2>&1 || { echo "jq is required but not installed."; exit 1; }

PASS_COUNT=0
FAIL_COUNT=0

TENANT_CODE="ext-test-$(date +%s)"

make_request() {
  local method=$1
  local url=$2
  local payload=$3
  shift 3
  local headers=("$@")

  if [ "$method" = "GET" ]; then
    curl -s -S -X GET "${headers[@]}" "$url"
  elif [ -n "$payload" ]; then
    curl -s -S -X "$method" "${headers[@]}" -H "Content-Type: application/json" -d "$payload" "$url"
  else
    curl -s -S -X "$method" "${headers[@]}" -H "Content-Type: application/json" "$url"
  fi
}

assert_code_zero() {
  local name=$1
  local response=$2
  local code
  code=$(echo "$response" | jq -r '.code // .errcode // empty')

  if [ "$code" = "0" ]; then
    echo "[PASS] $name"
    PASS_COUNT=$((PASS_COUNT + 1))
    return 0
  else
    echo "[FAIL] $name (code=$code)"
    echo "       response: $response"
    FAIL_COUNT=$((FAIL_COUNT + 1))
    return 1
  fi
}

# 1. Create tenant
echo "==> 1. Create tenant"
TENANT_RESPONSE=$(make_request POST "$BASE_URL/api/v1/account/tenant" \
  '{"tenantCode":"'"$TENANT_CODE"'","tenantName":"External API Test"}')
assert_code_zero "Create tenant" "$TENANT_RESPONSE"

# 2. Create admin user and login
echo "==> 2. Create admin user and login"
USER_RESPONSE=$(make_request POST "$BASE_URL/api/v1/account/user" \
  '{"username":"admin","password":"admin123","realName":"Admin","roleCodes":["tenant_admin"]}' \
  -H "X-Tenant-Code: $TENANT_CODE")
assert_code_zero "Create admin user" "$USER_RESPONSE"

LOGIN_RESPONSE=$(make_request POST "$BASE_URL/api/v1/account/login" \
  '{"username":"admin","password":"admin123"}' \
  -H "X-Tenant-Code: $TENANT_CODE")
assert_code_zero "Login" "$LOGIN_RESPONSE"
TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.data.token')
AUTH_HEADER="Authorization: Bearer $TOKEN"

# 3. Create channel subject
echo "==> 3. Create channel subject"
SUBJECT_RESPONSE=$(make_request POST "$BASE_URL/api/v1/channel-subject" \
  '{"channelType":"wecom","subjectCode":"sino","subjectName":"Sino Test"}' \
  -H "$AUTH_HEADER" -H "X-Tenant-Code: $TENANT_CODE")
assert_code_zero "Create channel subject" "$SUBJECT_RESPONSE"

# 4. Create channel account
echo "==> 4. Create channel account"
ACCOUNT_RESPONSE=$(make_request POST "$BASE_URL/api/v1/channel-account" \
  '{"accountType":1,"channelType":"wecom","accountId":"ZhangSan","accountName":"张三"}' \
  -H "$AUTH_HEADER" -H "X-Tenant-Code: $TENANT_CODE")
assert_code_zero "Create channel account" "$ACCOUNT_RESPONSE"
ACCOUNT_ID=$(echo "$ACCOUNT_RESPONSE" | jq -r '.data.id')

# 5. Create conversation
echo "==> 5. Create conversation"
CONVERSATION_RESPONSE=$(make_request POST "$BASE_URL/api/v1/conversation" \
  '{"conversationType":2,"channelType":"wecom","channelConversationId":"room-test-'"$(date +%s)"'","conversationName":"Test Group"}' \
  -H "$AUTH_HEADER" -H "X-Tenant-Code: $TENANT_CODE")
assert_code_zero "Create conversation" "$CONVERSATION_RESPONSE"
CONVERSATION_ID=$(echo "$CONVERSATION_RESPONSE" | jq -r '.data.id')

# 6. Bind account to conversation
echo "==> 6. Bind account to conversation"
BIND_RESPONSE=$(make_request POST "$BASE_URL/api/v1/conversation/$CONVERSATION_ID/bind-account" \
  "{\"accountId\":$ACCOUNT_ID,\"bindingType\":1,\"sortOrder\":1}" \
  -H "$AUTH_HEADER" -H "X-Tenant-Code: $TENANT_CODE")
assert_code_zero "Bind account to conversation" "$BIND_RESPONSE"

# 7. Test send
echo "==> 7. Test send"
SEND_RESPONSE=$(make_request POST "$BASE_URL/api/v1/send/test" \
  "{\"targetType\":\"conversation\",\"targetValue\":{\"conversation_id\":$CONVERSATION_ID},\"contentType\":\"text\",\"content\":{\"text\":\"hello from external api test\"},\"channelStrategy\":{\"channel_type\":\"wecom\",\"strategy\":\"primary\"}}" \
  -H "$AUTH_HEADER" -H "X-Tenant-Code: $TENANT_CODE")
assert_code_zero "Test send" "$SEND_RESPONSE"
TASK_ID=$(echo "$SEND_RESPONSE" | jq -r '.data.taskId')

# 8. Query send records
echo "==> 8. Query send records"
RECORDS_RESPONSE=$(make_request GET "$BASE_URL/api/v1/send/$TASK_ID/records" "" \
  -H "$AUTH_HEADER" -H "X-Tenant-Code: $TENANT_CODE")
assert_code_zero "Query send records" "$RECORDS_RESPONSE"

# 9. Receive inbound message
echo "==> 9. Receive inbound message"
EVENT_ID="evt-$(date +%s)-$RANDOM"
INBOUND_RESPONSE=$(make_request POST "$BASE_URL/api/v1/inbound/receive" \
  "{\"eventId\":\"$EVENT_ID\",\"channelType\":\"wecom\",\"channelSubjectId\":1,\"eventType\":\"message\",\"messageSource\":\"realtime\",\"conversationId\":$CONVERSATION_ID,\"accountId\":$ACCOUNT_ID,\"content\":{\"text\":\"hello inbound\"},\"rawPayload\":{},\"businessContext\":{}}" \
  -H "$AUTH_HEADER" -H "X-Tenant-Code: $TENANT_CODE")
assert_code_zero "Receive inbound message" "$INBOUND_RESPONSE"

# 10. Channel-service health
echo "==> 10. Channel-service health"
HEALTH_RESPONSE=$(curl -s -S "$CHANNEL_URL/health")
if echo "$HEALTH_RESPONSE" | jq -e '.status == "ok"' >/dev/null 2>&1; then
  echo "[PASS] Channel-service health"
  PASS_COUNT=$((PASS_COUNT + 1))
else
  echo "[FAIL] Channel-service health"
  echo "       response: $HEALTH_RESPONSE"
  FAIL_COUNT=$((FAIL_COUNT + 1))
fi

# 11. WeChat personal login start
echo "==> 11. WeChat personal login start"
LOGIN_RESPONSE=$(make_request POST "$CHANNEL_URL/v1/wechat-personal/login/start" \
  '{"account_id":"bot-test-'"$(date +%s)"'","account_name":"Test Bot"}')
if echo "$LOGIN_RESPONSE" | jq -e '.login_id' >/dev/null 2>&1; then
  echo "[PASS] WeChat personal login start"
  PASS_COUNT=$((PASS_COUNT + 1))
else
  echo "[FAIL] WeChat personal login start"
  echo "       response: $LOGIN_RESPONSE"
  FAIL_COUNT=$((FAIL_COUNT + 1))
fi

# 12. WeChat personal send text (after confirming a login)
echo "==> 12. WeChat personal send text"
BOT_ID="bot-send-$(date +%s)"
make_request POST "$CHANNEL_URL/v1/wechat-personal/login/start" \
  '{"account_id":"'"$BOT_ID"'"}' >/dev/null
make_request POST "$CHANNEL_URL/v1/wechat-personal/login/$BOT_ID/confirm" "{}" >/dev/null
SEND_TEXT_RESPONSE=$(make_request POST "$CHANNEL_URL/v1/wechat-personal/send/text" \
  '{"account_id":"'"$BOT_ID"'","conversation_id":"room-test","text":"hello"}')
if echo "$SEND_TEXT_RESPONSE" | jq -e '.success == true' >/dev/null 2>&1; then
  echo "[PASS] WeChat personal send text"
  PASS_COUNT=$((PASS_COUNT + 1))
else
  echo "[FAIL] WeChat personal send text"
  echo "       response: $SEND_TEXT_RESPONSE"
  FAIL_COUNT=$((FAIL_COUNT + 1))
fi

echo ""
echo "========================="
echo "Total: $((PASS_COUNT + FAIL_COUNT)), Passed: $PASS_COUNT, Failed: $FAIL_COUNT"
echo "========================="

if [ "$FAIL_COUNT" -gt 0 ]; then
  exit 1
fi
