#!/bin/bash
set -e

# Configuration
API_URL="http://localhost:8080/api/v1"
CHAT_URL="http://localhost:8081"
EMAIL_B="user_b_$(date +%s)@example.com"
USERNAME_B="user_b_$(date +%s)"
PASSWORD="Password123!"

# Colors
GREEN='\033[0;32m'
MAGENTA='\033[0;35m'
NC='\033[0m'

log() {
    echo -e "${MAGENTA}[USER B & CHAT] $1${NC}"
}

success() {
    echo -e "${GREEN}  ✅ $1${NC}"
}

# Load User A info
if [ -f .user_a_env ]; then
    source .user_a_env
    TOKEN_A=$ACCESS_TOKEN
    USER_ID_A=$USER_ID
else
    echo "User A env not found, run smoke_user_a.sh first"
    exit 1
fi

# 1. Inscription User B
log "1. Registering User B..."
REGISTER_RES=$(curl -s -X POST "$API_URL/auth/register" \
  -H "Content-Type: application/json" \
  -d "{
    \"email\": \"$EMAIL_B\",
    \"username\": \"$USERNAME_B\",
    \"password\": \"$PASSWORD\"
  }")

TOKEN_B=$(echo $REGISTER_RES | jq -r '.access_token')
USER_ID_B=$(echo $REGISTER_RES | jq -r '.user.id')

if [ "$TOKEN_B" != "null" ] && [ -n "$TOKEN_B" ]; then
    success "User B registered: $USER_ID_B"
else
    echo "User B registration failed: $REGISTER_RES"
    exit 1
fi

# 2. Create Room
# Based on discovered handlers, we have POST /rooms via room_handlers.go or chat_handlers.go
# Assuming standard POST /rooms or /chat/rooms based on router.
# Let's try POST /api/v1/rooms based on usual REST conventions for 'rooms' resource
log "2. Creating chat room..."

ROOM_RES=$(curl -s -X POST "$API_URL/rooms" \
  -H "Authorization: Bearer $TOKEN_A" \
  -H "Content-Type: application/json" \
  -d "{
    \"name\": \"Test Room\",
    \"room_type\": \"public\",
    \"max_members\": 10
  }")

ROOM_ID=$(echo $ROOM_RES | jq -r '.id')

if [ "$ROOM_ID" != "null" ] && [ -n "$ROOM_ID" ]; then
    success "Room created: $ROOM_ID"
else
    # Fallback log if room creation endpoint differs or fails
    log "  ⚠️ Room creation returned null ID or failed. Response: $ROOM_RES"
    log "  (Skipping explicit room join check, will use placeholder ID for manual test doc)"
    ROOM_ID="manual_room_id"
fi

# 3. WS Token
# If the architecture uses the main JWT for WS, we already have TOKEN_A and TOKEN_B.
log "3. Using main JWT tokens for WebSocket auth (standard Veza flow)."

# 4. Generate WS Test Instructions
log "4. Generating WebSocket test instructions..."

cat <<EOF > scripts/chat_ws_test.md
# WebSocket Chat Test Instructions

## Prerequisites
- Install \`websocat\` (e.g., \`cargo install websocat\` or \`brew install websocat\`)

## Credentials
User A Token: 
\`$TOKEN_A\`

User B Token: 
\`$TOKEN_B\`

Room ID: 
\`$ROOM_ID\`

## Manual Test Steps

1. **Connect User A**:
   \`\`\`bash
   # Adjust the URL query params based on specific chat server implementation
   # Common pattern: ws://localhost:8081/ws?token=...
   websocat "ws://localhost:8081/ws?token=$TOKEN_A"
   \`\`\`

2. **Connect User B** (in a new terminal):
   \`\`\`bash
   websocat "ws://localhost:8081/ws?token=$TOKEN_B"
   \`\`\`

3. **Join Room (if required protocol-side)**:
   A & B might need to send a join message first:
   \`\`\`json
   {"type": "join_room", "room_id": "$ROOM_ID"}
   \`\`\`

4. **Send Message from A**:
   Paste this JSON into User A's terminal:
   \`\`\`json
   {"type": "message", "room_id": "$ROOM_ID", "content": "Hello from A", "message_type": "text"}
   \`\`\`

5. **Verify**:
   - User B should receive the message payload.
   - User A might receive an ack or the echoed message.

EOF

success "Instructions generated in scripts/chat_ws_test.md"
log "✅ Scenario User B setup complete!"
