#!/bin/bash
# Test Parcours Utilisateur Complet - Veza Publication Readiness
# Ce script teste tous les parcours utilisateur critiques

set -e

API="http://localhost:8080/api/v1"
TS=$(date +%s)
EMAIL="user${TS}@test.com"
USERNAME="user${TS}"
PASSWORD='Xk9$mP2#vL7@nQ4!wR8'

echo "=== TEST PARCOURS UTILISATEUR COMPLET ==="
echo "📧 Email: $EMAIL"
echo "👤 Username: $USERNAME"
echo ""

# Variables pour le rapport
REG_SUCCESS=false
LOGIN_SUCCESS=false
TOKEN=""
ME_SUCCESS=false
TRACK_CREATE_SUCCESS=false
TRACK_ID=""
TRACKS_LIST_SUCCESS=false
PLAYLIST_CREATE_SUCCESS=false
PLAYLIST_ID=""
PLAYLISTS_LIST_SUCCESS=false
SEARCH_SUCCESS=false
LOGOUT_SUCCESS=false

# 1. INSCRIPTION
echo "1️⃣ INSCRIPTION"
REG=$(curl -s -X POST "$API/auth/register" \
  -H "Content-Type: application/json" \
  -d "{\"email\":\"$EMAIL\",\"username\":\"$USERNAME\",\"password\":\"$PASSWORD\",\"password_confirm\":\"$PASSWORD\"}")

REG_SUCCESS_VAL=$(echo "$REG" | jq -r '.success // .data.success // false' 2>/dev/null || echo "false")
if [ "$REG_SUCCESS_VAL" = "true" ]; then
  REG_SUCCESS=true
  echo "✅ Inscription réussie"
else
  REG_ERROR=$(echo "$REG" | jq -r '.error.message // .message // .error // .' 2>/dev/null || echo "$REG")
  echo "❌ Échec inscription: $REG_ERROR"
fi
echo ""

# 2. CONNEXION
echo "2️⃣ CONNEXION"
LOGIN=$(curl -s -X POST "$API/auth/login" \
  -H "Content-Type: application/json" \
  -d "{\"email\":\"$EMAIL\",\"password\":\"$PASSWORD\"}")

TOKEN=$(echo "$LOGIN" | jq -r '.data.token.access_token // .data.access_token // .token.access_token // empty' 2>/dev/null || echo "")
if [ -n "$TOKEN" ] && [ "$TOKEN" != "null" ]; then
  LOGIN_SUCCESS=true
  echo "✅ Token obtenu"
else
  LOGIN_ERROR=$(echo "$LOGIN" | jq -r '.error.message // .message // .error // .' 2>/dev/null || echo "$LOGIN")
  echo "❌ Échec connexion: $LOGIN_ERROR"
  echo "Réponse complète: $LOGIN"
fi
echo ""

if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then
  echo "❌ ÉCHEC CRITIQUE: Impossible d'obtenir un token"
  echo "=== RÉSUMÉ PARTIEL ==="
  echo "✅ Inscription: $REG_SUCCESS"
  echo "✅ Login: false"
  exit 1
fi

# 3. PROFIL UTILISATEUR
echo "3️⃣ PROFIL UTILISATEUR"
ME=$(curl -s "$API/auth/me" -H "Authorization: Bearer $TOKEN")
ME_SUCCESS_VAL=$(echo "$ME" | jq -r '.success // .data.email // false' 2>/dev/null || echo "false")
if [ "$ME_SUCCESS_VAL" != "false" ] && [ -n "$(echo "$ME" | jq -r '.data.email // .email // empty' 2>/dev/null)" ]; then
  ME_SUCCESS=true
  ME_EMAIL=$(echo "$ME" | jq -r '.data.email // .email // "N/A"' 2>/dev/null || echo "N/A")
  echo "✅ Profil récupéré: $ME_EMAIL"
else
  ME_ERROR=$(echo "$ME" | jq -r '.error.message // .message // .error // .' 2>/dev/null || echo "$ME")
  echo "❌ Échec récupération profil: $ME_ERROR"
fi
echo ""

# 4. CRÉER UN TRACK
echo "4️⃣ CRÉER UN TRACK"
TRACK=$(curl -s -X POST "$API/tracks" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"title":"Ma Première Chanson","genre":"Pop","description":"Test track"}')

TRACK_ID=$(echo "$TRACK" | jq -r '.data.id // .id // empty' 2>/dev/null || echo "")
if [ -n "$TRACK_ID" ] && [ "$TRACK_ID" != "null" ]; then
  TRACK_CREATE_SUCCESS=true
  echo "✅ Track créé: ID=$TRACK_ID"
else
  TRACK_ERROR=$(echo "$TRACK" | jq -r '.error.message // .message // .error // .' 2>/dev/null || echo "$TRACK")
  echo "❌ Échec création track: $TRACK_ERROR"
fi
echo ""

# 5. LISTER LES TRACKS
echo "5️⃣ LISTER LES TRACKS"
TRACKS=$(curl -s "$API/tracks" -H "Authorization: Bearer $TOKEN")
TRACKS_COUNT=$(echo "$TRACKS" | jq -r '.data | length // . | length // 0' 2>/dev/null || echo "0")
if [ "$TRACKS_COUNT" -ge 0 ]; then
  TRACKS_LIST_SUCCESS=true
  echo "✅ Nombre de tracks: $TRACKS_COUNT"
else
  TRACKS_ERROR=$(echo "$TRACKS" | jq -r '.error.message // .message // .error // .' 2>/dev/null || echo "$TRACKS")
  echo "❌ Échec liste tracks: $TRACKS_ERROR"
fi
echo ""

# 6. CRÉER UNE PLAYLIST
echo "6️⃣ CRÉER UNE PLAYLIST"
PLAYLIST=$(curl -s -X POST "$API/playlists" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"title":"Ma Playlist","description":"Mes favoris","visibility":"private"}')

PLAYLIST_ID=$(echo "$PLAYLIST" | jq -r '.data.id // .id // empty' 2>/dev/null || echo "")
if [ -n "$PLAYLIST_ID" ] && [ "$PLAYLIST_ID" != "null" ]; then
  PLAYLIST_CREATE_SUCCESS=true
  echo "✅ Playlist créée: ID=$PLAYLIST_ID"
else
  PLAYLIST_ERROR=$(echo "$PLAYLIST" | jq -r '.error.message // .message // .error // .' 2>/dev/null || echo "$PLAYLIST")
  echo "❌ Échec création playlist: $PLAYLIST_ERROR"
fi
echo ""

# 7. LISTER LES PLAYLISTS
echo "7️⃣ LISTER LES PLAYLISTS"
PLAYLISTS=$(curl -s "$API/playlists" -H "Authorization: Bearer $TOKEN")
PLAYLISTS_COUNT=$(echo "$PLAYLISTS" | jq -r '.data | length // . | length // 0' 2>/dev/null || echo "0")
if [ "$PLAYLISTS_COUNT" -ge 0 ]; then
  PLAYLISTS_LIST_SUCCESS=true
  echo "✅ Nombre de playlists: $PLAYLISTS_COUNT"
else
  PLAYLISTS_ERROR=$(echo "$PLAYLISTS" | jq -r '.error.message // .message // .error // .' 2>/dev/null || echo "$PLAYLISTS")
  echo "❌ Échec liste playlists: $PLAYLISTS_ERROR"
fi
echo ""

# 8. RECHERCHE
echo "8️⃣ RECHERCHE"
SEARCH=$(curl -s "$API/tracks/search?q=chanson" -H "Authorization: Bearer $TOKEN" 2>/dev/null || echo '{"error":"endpoint_not_found"}')
SEARCH_COUNT=$(echo "$SEARCH" | jq -r '.data | length // . | length // 0' 2>/dev/null || echo "0")
if echo "$SEARCH" | jq -e '.data' >/dev/null 2>&1 || [ "$SEARCH_COUNT" -ge 0 ]; then
  SEARCH_SUCCESS=true
  echo "✅ Résultats recherche 'chanson': $SEARCH_COUNT"
else
  echo "⚠️ Recherche: endpoint non disponible ou erreur"
fi
echo ""

# 9. DÉCONNEXION
echo "9️⃣ DÉCONNEXION"
REFRESH=$(echo "$LOGIN" | jq -r '.data.token.refresh_token // .data.refresh_token // .refresh_token // empty' 2>/dev/null || echo "")
if [ -n "$REFRESH" ] && [ "$REFRESH" != "null" ]; then
  LOGOUT=$(curl -s -X POST "$API/auth/logout" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d "{\"refresh_token\":\"$REFRESH\"}")
  LOGOUT_SUCCESS_VAL=$(echo "$LOGOUT" | jq -r '.success // false' 2>/dev/null || echo "false")
  if [ "$LOGOUT_SUCCESS_VAL" = "true" ]; then
    LOGOUT_SUCCESS=true
    echo "✅ Déconnexion réussie"
  else
    LOGOUT_ERROR=$(echo "$LOGOUT" | jq -r '.error.message // .message // .error // .' 2>/dev/null || echo "$LOGOUT")
    echo "❌ Échec déconnexion: $LOGOUT_ERROR"
  fi
else
  echo "⚠️ Refresh token non disponible, test de déconnexion ignoré"
fi
echo ""

# 10. VÉRIFIER QUE LA SESSION EST INVALIDE (si logout réussi)
if [ "$LOGOUT_SUCCESS" = true ]; then
  echo "🔟 VÉRIFIER SESSION INVALIDE"
  VERIFY=$(curl -s "$API/auth/me" -H "Authorization: Bearer $TOKEN")
  VERIFY_ERROR=$(echo "$VERIFY" | jq -r '.error.message // .message // .error // empty' 2>/dev/null || echo "")
  if [ -n "$VERIFY_ERROR" ]; then
    echo "✅ Session invalidée correctement"
  else
    echo "⚠️ Session toujours valide après logout"
  fi
  echo ""
fi

# RÉSUMÉ
echo "=== RÉSUMÉ ==="
echo "✅ Inscription: $REG_SUCCESS"
echo "✅ Login: $LOGIN_SUCCESS"
echo "✅ Profil: $ME_SUCCESS"
echo "✅ Créer track: $TRACK_CREATE_SUCCESS"
echo "✅ Lister tracks: $TRACKS_LIST_SUCCESS"
echo "✅ Créer playlist: $PLAYLIST_CREATE_SUCCESS"
echo "✅ Lister playlists: $PLAYLISTS_LIST_SUCCESS"
echo "✅ Recherche: $SEARCH_SUCCESS"
echo "✅ Logout: $LOGOUT_SUCCESS"

# Export pour utilisation dans le script principal
export REG_SUCCESS LOGIN_SUCCESS ME_SUCCESS TRACK_CREATE_SUCCESS TRACKS_LIST_SUCCESS \
       PLAYLIST_CREATE_SUCCESS PLAYLISTS_LIST_SUCCESS SEARCH_SUCCESS LOGOUT_SUCCESS

