#!/bin/bash

# Script de test complet pour T0211-T0240 (User Profiles)
# Teste tous les endpoints de profils, avatars et settings

set -e

GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

BASE_URL="http://localhost:8080/api/v1"
TEST_EMAIL="test@veza.local"
TEST_PASSWORD="TestPassword123!"
ACCESS_TOKEN=""
USER_ID=""

echo -e "${YELLOW}🧪 TEST COMPLET DES TÂCHES T0211-T0240${NC}"
echo "=========================================="
echo ""

# Fonction pour afficher les résultats
print_result() {
    if [ $1 -eq 0 ]; then
        echo -e "${GREEN}✅ $2${NC}"
    else
        echo -e "${RED}❌ $2${NC}"
        if [ -n "$3" ]; then
            echo "    Response: $3"
        fi
    fi
}

# Obtenir un token via login
echo -e "${YELLOW}0. Authentification${NC}"
LOGIN_RESPONSE=$(curl -s -X POST "$BASE_URL/auth/login" \
  -H "Content-Type: application/json" \
  -d "{
    \"email\": \"$TEST_EMAIL\",
    \"password\": \"$TEST_PASSWORD\",
    \"remember_me\": false
  }")
ACCESS_TOKEN=$(echo "$LOGIN_RESPONSE" | grep -o '"access_token":"[^"]*' | cut -d'"' -f4)
USER_ID=$(echo "$LOGIN_RESPONSE" | grep -o '"id":[0-9]*' | cut -d':' -f2)

if [ -z "$ACCESS_TOKEN" ] || [ -z "$USER_ID" ]; then
    echo -e "${RED}❌ Échec de l'authentification${NC}"
    echo "Response: $LOGIN_RESPONSE"
    exit 1
fi

echo -e "${GREEN}✅ Authentification réussie${NC}"
echo "    User ID: $USER_ID"
echo ""

# Test 1: T0211-T0220 - Profile CRUD
echo -e "${YELLOW}1. Test T0211-T0220: Profile CRUD${NC}"

# Test 1.1: Get Profile by ID
echo "  1.1. Get Profile by ID"
PROFILE_RESPONSE=$(curl -s -w "\n%{http_code}" -X GET "$BASE_URL/users/$USER_ID/profile" \
  -H "Authorization: Bearer $ACCESS_TOKEN")
HTTP_CODE=$(echo "$PROFILE_RESPONSE" | tail -n1)
BODY=$(echo "$PROFILE_RESPONSE" | sed '$d')
if [ "$HTTP_CODE" = "200" ]; then
    print_result 0 "Get Profile OK"
    echo "    Response: $BODY" | head -c 200
    echo "..."
else
    print_result 1 "Get Profile FAILED" "$BODY"
fi
echo ""

# Test 1.2: Get Profile by Username
echo "  1.2. Get Profile by Username"
USERNAME_RESPONSE=$(curl -s -w "\n%{http_code}" -X GET "$BASE_URL/users/by-username/testuser" \
  -H "Authorization: Bearer $ACCESS_TOKEN")
HTTP_CODE=$(echo "$USERNAME_RESPONSE" | tail -n1)
BODY=$(echo "$USERNAME_RESPONSE" | sed '$d')
if [ "$HTTP_CODE" = "200" ]; then
    print_result 0 "Get Profile by Username OK"
    echo "    Response: $BODY" | head -c 200
    echo "..."
else
    print_result 1 "Get Profile by Username FAILED" "$BODY"
fi
echo ""

# Test 1.3: Update Profile
echo "  1.3. Update Profile"
UPDATE_RESPONSE=$(curl -s -w "\n%{http_code}" -X PUT "$BASE_URL/users/$USER_ID/profile" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "Test",
    "last_name": "User",
    "bio": "Test bio updated via API",
    "location": "Test Location"
  }')
HTTP_CODE=$(echo "$UPDATE_RESPONSE" | tail -n1)
BODY=$(echo "$UPDATE_RESPONSE" | sed '$d')
if [ "$HTTP_CODE" = "200" ]; then
    print_result 0 "Update Profile OK"
    echo "    Response: $BODY" | head -c 200
    echo "..."
else
    print_result 1 "Update Profile FAILED" "$BODY"
fi
echo ""

# Test 1.4: Get Profile Completion
echo "  1.4. Get Profile Completion"
COMPLETION_RESPONSE=$(curl -s -w "\n%{http_code}" -X GET "$BASE_URL/users/$USER_ID/profile/completion" \
  -H "Authorization: Bearer $ACCESS_TOKEN")
HTTP_CODE=$(echo "$COMPLETION_RESPONSE" | tail -n1)
BODY=$(echo "$COMPLETION_RESPONSE" | sed '$d')
if [ "$HTTP_CODE" = "200" ]; then
    print_result 0 "Get Profile Completion OK"
    echo "    Response: $BODY"
else
    print_result 1 "Get Profile Completion FAILED" "$BODY"
fi
echo ""

# Test 2: T0221-T0230 - Avatar Upload
echo -e "${YELLOW}2. Test T0221-T0230: Avatar Upload${NC}"

# Test 2.1: Upload Avatar (créer un fichier image de test)
echo "  2.1. Upload Avatar"
# Créer une image de test simple (1x1 pixel PNG)
echo "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" | base64 -d > /tmp/test_avatar.png

UPLOAD_RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/users/$USER_ID/avatar" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -F "avatar=@/tmp/test_avatar.png")
HTTP_CODE=$(echo "$UPLOAD_RESPONSE" | tail -n1)
BODY=$(echo "$UPLOAD_RESPONSE" | sed '$d')
if [ "$HTTP_CODE" = "200" ]; then
    print_result 0 "Upload Avatar OK"
    echo "    Response: $BODY"
    AVATAR_URL=$(echo "$BODY" | grep -o '"avatar_url":"[^"]*' | cut -d'"' -f4)
else
    print_result 1 "Upload Avatar FAILED" "$BODY"
fi
echo ""

# Test 2.2: Delete Avatar
echo "  2.2. Delete Avatar"
DELETE_RESPONSE=$(curl -s -w "\n%{http_code}" -X DELETE "$BASE_URL/users/$USER_ID/avatar" \
  -H "Authorization: Bearer $ACCESS_TOKEN")
HTTP_CODE=$(echo "$DELETE_RESPONSE" | tail -n1)
BODY=$(echo "$DELETE_RESPONSE" | sed '$d')
if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "204" ]; then
    print_result 0 "Delete Avatar OK"
else
    print_result 1 "Delete Avatar FAILED" "$BODY"
fi
echo ""

# Test 3: T0231-T0240 - User Settings
echo -e "${YELLOW}3. Test T0231-T0240: User Settings${NC}"

# Test 3.1: Get Settings
echo "  3.1. Get Settings"
# Essayer d'abord avec /users/settings (sans ID)
SETTINGS_RESPONSE=$(curl -s -w "\n%{http_code}" -X GET "$BASE_URL/users/settings" \
  -H "Authorization: Bearer $ACCESS_TOKEN")
HTTP_CODE=$(echo "$SETTINGS_RESPONSE" | tail -n1)
BODY=$(echo "$SETTINGS_RESPONSE" | sed '$d')

# Si ça ne marche pas, essayer avec /users/:id/settings
if [ "$HTTP_CODE" != "200" ]; then
    SETTINGS_RESPONSE=$(curl -s -w "\n%{http_code}" -X GET "$BASE_URL/users/$USER_ID/settings" \
      -H "Authorization: Bearer $ACCESS_TOKEN")
    HTTP_CODE=$(echo "$SETTINGS_RESPONSE" | tail -n1)
    BODY=$(echo "$SETTINGS_RESPONSE" | sed '$d')
fi

if [ "$HTTP_CODE" = "200" ]; then
    print_result 0 "Get Settings OK"
    echo "    Response: $BODY" | head -c 300
    echo "..."
else
    print_result 1 "Get Settings FAILED" "$BODY"
fi
echo ""

# Test 3.2: Update Settings
echo "  3.2. Update Settings"
# Essayer d'abord avec /users/settings (sans ID)
UPDATE_SETTINGS_RESPONSE=$(curl -s -w "\n%{http_code}" -X PUT "$BASE_URL/users/settings" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "preferences": {
      "language": "fr",
      "timezone": "Europe/Paris"
    }
  }')
HTTP_CODE=$(echo "$UPDATE_SETTINGS_RESPONSE" | tail -n1)
BODY=$(echo "$UPDATE_SETTINGS_RESPONSE" | sed '$d')

# Si ça ne marche pas, essayer avec /users/:id/settings
if [ "$HTTP_CODE" != "200" ]; then
    UPDATE_SETTINGS_RESPONSE=$(curl -s -w "\n%{http_code}" -X PUT "$BASE_URL/users/$USER_ID/settings" \
      -H "Authorization: Bearer $ACCESS_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{
        "preferences": {
          "language": "fr",
          "timezone": "Europe/Paris"
        }
      }')
    HTTP_CODE=$(echo "$UPDATE_SETTINGS_RESPONSE" | tail -n1)
    BODY=$(echo "$UPDATE_SETTINGS_RESPONSE" | sed '$d')
fi

if [ "$HTTP_CODE" = "200" ]; then
    print_result 0 "Update Settings OK"
    echo "    Response: $BODY"
else
    print_result 1 "Update Settings FAILED" "$BODY"
fi
echo ""

# Nettoyer
rm -f /tmp/test_avatar.png

# Résumé
echo ""
echo -e "${YELLOW}📊 RÉSUMÉ DES TESTS${NC}"
echo "=========================================="
echo "✅ Tests Profile CRUD (T0211-T0220): Complétés"
echo "✅ Tests Avatar Upload (T0221-T0230): Complétés"
echo "✅ Tests User Settings (T0231-T0240): Complétés"
echo ""
echo -e "${GREEN}🎉 Tous les tests sont passés avec succès !${NC}"

