#!/bin/bash
set -euo pipefail

# Configuration
API_PORT=8080
CHAT_PORT=8081
API_URL="http://localhost:$API_PORT/api/v1"

# User B Data
TIMESTAMP=$(date +%s)
EMAIL="userb_${TIMESTAMP}@example.com"
USERNAME="userb_${TIMESTAMP}"
PASSWORD="Password123!"

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

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

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

error() {
    echo -e "${RED}[ERROR] $1${NC}"
    exit 1
}

# Ensure jq is installed
if ! command -v jq &> /dev/null; then
    error "jq is required but not installed."
fi

# Load User A Data
if [ -f .user_a_env ]; then
    source .user_a_env
else
    error "User A environment file (.user_a_env) not found. Run smoke_user_a.sh first."
fi

# 1. Inscription / Login 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\",
    \"username\": \"$USERNAME\",
    \"password\": \"$PASSWORD\",
    \"password_confirm\": \"$PASSWORD\"
  }")

# Auto-verify email in DB
log "  Verifying user email in DB..."
docker compose exec -T postgres psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "UPDATE users SET is_verified = true WHERE email = '$EMAIL';" > /dev/null

ACCESS_B=$(echo "$REGISTER_RES" | jq -r '.access_token')

if [ "$ACCESS_B" == "null" ] || [ -z "$ACCESS_B" ]; then
    # Try login if already registered (idempotency)
    LOGIN_RES=$(curl -s -X POST "$API_URL/auth/login" \
      -H "Content-Type: application/json" \
      -d "{ \"email\": \"$EMAIL\", \"password\": \"$PASSWORD\" }")
    ACCESS_B=$(echo "$LOGIN_RES" | jq -r '.token.access_token')
fi

if [ "$ACCESS_B" == "null" ] || [ -z "$ACCESS_B" ]; then
    error "Could not register or login User B."
fi

success "User B authenticated"

# 2. Création / Choix d'une Room
log "2. Setting up Chat Room..."
# Try to create a room via User A
ROOM_RES=$(curl -s -X POST "$API_URL/conversations" \
  -H "Authorization: Bearer $ACCESS_A" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Smoke Test Room",
    "type": "public"
  }')

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

if [ -z "$ROOM_ID" ] || [ "$ROOM_ID" == "null" ]; then
    log "  (Creation failed: $ROOM_RES)"
    # Fallback: List rooms and pick one
    log "  (Creation failed or returned no ID, trying to list rooms)"
    LIST_RES=$(curl -s -H "Authorization: Bearer $ACCESS_A" "$API_URL/conversations")
    ROOM_ID=$(echo "$LIST_RES" | jq -r '.conversations[0].id // empty')
fi

if [ -z "$ROOM_ID" ] || [ "$ROOM_ID" == "null" ]; then
    # Hard fallback for manual testing if API is mocked or empty
    ROOM_ID="room_1"
    log "  ⚠️ Using fallback Room ID: $ROOM_ID"
else
    success "Room ID secured: $ROOM_ID"
fi

# 3. Token WebSocket
log "3. Fetching WebSocket tokens..."

# Fetch for A
# Assuming endpoint /chat/token exists based on handlers
WS_TOKEN_A_RES=$(curl -s -X POST "$API_URL/chat/token" -H "Authorization: Bearer $ACCESS_A")
WS_TOKEN_A=$(echo "$WS_TOKEN_A_RES" | jq -r '.token // empty')

if [ -z "$WS_TOKEN_A" ] || [ "$WS_TOKEN_A" == "null" ]; then
    # Fallback: Use JWT as WS token if no specific endpoint
    WS_TOKEN_A=$ACCESS_A
    log "  (Using main Access Token for A)"
fi

# Fetch for B
WS_TOKEN_B_RES=$(curl -s -X POST "$API_URL/chat/token" -H "Authorization: Bearer $ACCESS_B")
WS_TOKEN_B=$(echo "$WS_TOKEN_B_RES" | jq -r '.token // empty')

if [ -z "$WS_TOKEN_B" ] || [ "$WS_TOKEN_B" == "null" ]; then
    # Fallback
    WS_TOKEN_B=$ACCESS_B
    log "  (Using main Access Token for B)"
fi

success "Tokens ready"

# 4. Generate Test Instructions
log "4. Generating CHAT_WEBSOCKET_TEST.md..."

cat <<EOF > docs/CHAT_WEBSOCKET_TEST.md
# 💬 Manuel de Test WebSocket (Chat)

Ce fichier est généré automatiquement par \`scripts/smoke_user_b_chat.sh\`.

## 1. Pré-requis
- Installer \`websocat\` :
  - Mac: \`brew install websocat\`
  - Linux: \`cargo install websocat\` ou binaire statique.

## 2. Variables de Session
- **Chat Server URL**: \`ws://localhost:$CHAT_PORT/ws\`
- **Room ID**: \`$ROOM_ID\`

### User A
- **Token**: 
\`$WS_TOKEN_A\`

### User B
- **Token**: 
\`$WS_TOKEN_B\`

## 3. Scénario de Test

### Étape A : Connecter User A
Ouvrir un terminal et lancer :
\`\`\`bash
websocat "ws://localhost:$CHAT_PORT/ws?token=$WS_TOKEN_A"
\`\`\`
*Si nécessaire, ajouter \`&roomId=$ROOM_ID\` ou envoyer un message de join.*

### Étape B : Connecter User B
Ouvrir un **autre** terminal et lancer :
\`\`\`bash
websocat "ws://localhost:$CHAT_PORT/ws?token=$WS_TOKEN_B"
\`\`\`

### Étape C : Échange de messages
Dans le terminal de **User A**, coller ce JSON (basé sur le protocole frontend Veza) :
\`\`\`json
{
  "type": "SendMessage",
  "conversation_id": "$ROOM_ID",
  "content": "Hello from User A!",
  "parent_message_id": null
}
\`\`\`

**Attendu** : 
1. Le message apparaît dans le terminal de **User B** (format JSON type \`NewMessage\`).
2. User B peut répondre de la même manière (en inversant les rôles).
EOF

success "Documentation generated in docs/CHAT_WEBSOCKET_TEST.md"
log "✅ User B & Chat Setup OK"

