#!/bin/bash
set -euo pipefail

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

# Unique user data based on timestamp
TIMESTAMP=$(date +%s)
EMAIL="usera_${TIMESTAMP}@example.com"
USERNAME="usera_${TIMESTAMP}"
PASSWORD="Password123!"

# Colors
BLUE='\033[0;34m'
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

log() {
    echo -e "${BLUE}[USER A] $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

# 1. Inscription
log "1. Registering User A ($EMAIL)..."
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 (for testing purposes)
log "  Verifying user email in DB..."
if docker compose exec -T postgres psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "UPDATE users SET is_verified = true WHERE email = '$EMAIL';"; then
    success "Email verified in DB"
else
    error "Failed to verify email in DB"
fi


# Save for debugging
echo "$REGISTER_RES" > /tmp/veza_user_a_register.json

# Check for error
if echo "$REGISTER_RES" | jq -e '.error' > /dev/null; then
    ERR_MSG=$(echo "$REGISTER_RES" | jq -r '.error')
    error "Registration failed: $ERR_MSG"
fi

success "Registration OK"

# 2. Connexion
log "2. Logging in..."
LOGIN_RES=$(curl -s -X POST "$API_URL/auth/login" \
  -H "Content-Type: application/json" \
  -d "{
    \"email\": \"$EMAIL\",
    \"password\": \"$PASSWORD\"
  }")

ACCESS_A=$(echo "$LOGIN_RES" | jq -r '.token.access_token')
REFRESH_A=$(echo "$LOGIN_RES" | jq -r '.token.refresh_token')

if [ "$ACCESS_A" == "null" ] || [ -z "$ACCESS_A" ]; then
    error "Login failed, no access_token found. Response: $LOGIN_RES"
fi

# Save tokens for other scripts
echo "ACCESS_A=$ACCESS_A" > .user_a_env
echo "USER_ID_A=$(echo "$LOGIN_RES" | jq -r '.user.id')" >> .user_a_env

success "Login OK (Token extracted)"

# 3. Profil utilisateur
log "3. Checking profile..."
PROFILE_RES=$(curl -s -H "Authorization: Bearer $ACCESS_A" "$API_URL/auth/me")
PROFILE_EMAIL=$(echo "$PROFILE_RES" | jq -r '.email')

if [ "$PROFILE_EMAIL" != "$EMAIL" ]; then
    error "Profile mismatch. Expected $EMAIL, got $PROFILE_EMAIL"
fi

success "Profile verified ($PROFILE_EMAIL)"

# 4. Upload d’un track
log "4. Uploading track..."
mkdir -p tests/audio
# Generate dummy wav if not exists
if [ ! -f tests/audio/test_track.wav ]; then
    # Header only WAV
    echo -n -e '\x52\x49\x46\x46\x24\x00\x00\x00\x57\x41\x56\x45\x66\x6d\x74\x20\x10\x00\x00\x00\x01\x00\x01\x00\x44\xac\x00\x00\x88\x58\x01\x00\x02\x00\x10\x00\x64\x61\x74\x61\x00\x00\x00\x00' > tests/audio/test_track.wav
fi

UPLOAD_RES=$(curl -s -H "Authorization: Bearer $ACCESS_A" \
  -F "file=@tests/audio/test_track.wav" \
  -F "title=My Test Track" \
  -F "genre=Electronic" \
  "$API_URL/tracks")

TRACK_ID_A=$(echo "$UPLOAD_RES" | jq -r '.track.id')

if [ "$TRACK_ID_A" == "null" ] || [ -z "$TRACK_ID_A" ]; then
    error "Upload failed. Response: $UPLOAD_RES"
fi

success "Track uploaded (ID: $TRACK_ID_A)"

# 5. Statut streaming
log "5. Polling track status..."
MAX_RETRIES=10
COUNT=0
STREAM_READY=false

while [ $COUNT -lt $MAX_RETRIES ]; do
    STATUS_RES=$(curl -s -H "Authorization: Bearer $ACCESS_A" "$API_URL/tracks/$TRACK_ID_A")
    
    # Assuming the API returns the track object directly or status field
    # Adjust field name based on API implementation.
    # Here we check if we can retrieve it. Since we don't know the exact status field name for "ready"
    # (could be .status, .processingStatus, etc), we verify we get a 200 and the ID matches.
    
    RETRIEVED_ID=$(echo "$STATUS_RES" | jq -r '.track.id')
    
    if [ "$RETRIEVED_ID" == "$TRACK_ID_A" ]; then
        # In a real scenario, we would check a specific status field like:
        # STATUS=$(echo "$STATUS_RES" | jq -r '.status')
        # if [ "$STATUS" == "ready" ]; then ... fi
        
        # For this smoke test, retrieving the metadata successfully after upload is a good pass.
        STREAM_READY=true
        success "Track metadata available"
        break
    fi
    
    echo "   ... waiting for track (attempt $((COUNT+1))/$MAX_RETRIES)"
    sleep 2
    COUNT=$((COUNT+1))
done

if [ "$STREAM_READY" = false ]; then
    error "Track status polling timed out."
fi

# 6. Création d’une playlist
log "6. Creating playlist..."
PLAYLIST_RES=$(curl -s -X POST "$API_URL/playlists" \
  -H "Authorization: Bearer $ACCESS_A" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Playlist A",
    "description": "My awesome playlist",
    "is_public": true
  }')

PLAYLIST_ID_A=$(echo "$PLAYLIST_RES" | jq -r '.playlist.id')

if [ "$PLAYLIST_ID_A" == "null" ]; then
    error "Playlist creation failed. Response: $PLAYLIST_RES"
fi

success "Playlist created (ID: $PLAYLIST_ID_A)"

# 7. Ajout du track à la playlist
log "7. Adding track to playlist..."
ADD_RES=$(curl -s -X POST "$API_URL/playlists/$PLAYLIST_ID_A/tracks" \
  -H "Authorization: Bearer $ACCESS_A" \
  -H "Content-Type: application/json" \
  -d "{ \"track_id\": $TRACK_ID_A }") # Note: integer ID usually, no quotes if number

# Check if successful (usually 200 or 201)
# curl -s does not show HTTP code, checking response content implicitly via next step
success "Track add request sent"

# 8. Vérification de la playlist
log "8. Verifying playlist content..."
GET_PLAYLIST_RES=$(curl -s -H "Authorization: Bearer $ACCESS_A" "$API_URL/playlists/$PLAYLIST_ID_A")

# Check if track ID is present in the response
if echo "$GET_PLAYLIST_RES" | grep -q "$TRACK_ID_A"; then
    success "Track $TRACK_ID_A found in playlist $PLAYLIST_ID_A"
else
    error "Track not found in playlist. Response: $GET_PLAYLIST_RES"
fi

# Save playlist ID for other scripts/manual check
echo "PLAYLIST_ID_A=$PLAYLIST_ID_A" >> .user_a_env

log "✅ User A flow OK"
