#!/bin/bash

echo "🧪 Testing Avatar Update Functionality"
echo ""

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

# 1. Login as admin
echo "1️⃣ Logging in as admin..."
LOGIN_RESPONSE=$(curl -s -X POST http://localhost:8080/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@gauth.local","password":"Admin@123"}')

TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.access_token')

if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then
  echo -e "${RED}❌ Login failed!${NC}"
  echo "Response: $LOGIN_RESPONSE"
  exit 1
fi

echo -e "${GREEN}✅ Login successful${NC}"
echo "Token: ${TOKEN:0:30}..."
echo ""

# 2. Get user list
echo "2️⃣ Getting user list..."
USERS_RESPONSE=$(curl -s -X GET "http://localhost:8080/v1/admin/users?limit=5" \
  -H "Authorization: Bearer $TOKEN")

USER_ID=$(echo "$USERS_RESPONSE" | jq -r '.users[0].id')
USER_EMAIL=$(echo "$USERS_RESPONSE" | jq -r '.users[0].email')

if [ -z "$USER_ID" ] || [ "$USER_ID" = "null" ]; then
  echo -e "${RED}❌ Failed to get user ID${NC}"
  echo "Response: $USERS_RESPONSE"
  exit 1
fi

echo -e "${GREEN}✅ User found${NC}"
echo "User ID: $USER_ID"
echo "Email: $USER_EMAIL"
echo ""

# 3. Create test avatar
echo "3️⃣ Creating test avatar..."
# 1x1 red pixel PNG
echo "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==" | base64 -d > /tmp/test-avatar.png

if [ -f "/tmp/test-avatar.png" ]; then
  echo -e "${GREEN}✅ Test avatar created${NC}"
  ls -lh /tmp/test-avatar.png
else
  echo -e "${RED}❌ Failed to create test avatar${NC}"
  exit 1
fi
echo ""

# 4. Test 1: Upload avatar via /v1/user/avatar
echo "4️⃣ Test 1: Upload avatar via /v1/user/avatar..."
UPLOAD_RESPONSE=$(curl -s -X POST http://localhost:8080/v1/user/avatar \
  -H "Authorization: Bearer $TOKEN" \
  -F "avatar=@/tmp/test-avatar.png")

echo "Response:"
echo "$UPLOAD_RESPONSE" | jq .

if echo "$UPLOAD_RESPONSE" | jq -e '.avatar_url' > /dev/null 2>&1; then
  AVATAR_URL=$(echo "$UPLOAD_RESPONSE" | jq -r '.avatar_url')
  echo -e "${GREEN}✅ Avatar upload successful!${NC}"
  echo "Avatar URL: http://localhost:8080$AVATAR_URL"
else
  echo -e "${RED}❌ Avatar upload failed${NC}"
fi
echo ""

# 5. Test 2: Update user with new avatar via PUT /v1/admin/users/:id
echo "5️⃣ Test 2: Update user with avatar via PUT /v1/admin/users/:id..."

# Create a different test avatar (blue pixel)
echo "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" | base64 -d > /tmp/test-avatar-2.png

UPDATE_RESPONSE=$(curl -s -X PUT "http://localhost:8080/v1/admin/users/$USER_ID" \
  -H "Authorization: Bearer $TOKEN" \
  -F "user_name=Test Updated User" \
  -F "avatar=@/tmp/test-avatar-2.png")

echo "Response:"
echo "$UPDATE_RESPONSE" | jq .

if echo "$UPDATE_RESPONSE" | jq -e '.user.avatar' > /dev/null 2>&1; then
  NEW_AVATAR=$(echo "$UPDATE_RESPONSE" | jq -r '.user.avatar')
  echo -e "${GREEN}✅ User update with avatar successful!${NC}"
  echo "New Avatar URL: http://localhost:8080$NEW_AVATAR"

  # Check if avatar actually changed
  if [ "$NEW_AVATAR" != "$AVATAR_URL" ]; then
    echo -e "${GREEN}✅ Avatar URL changed!${NC}"
  else
    echo -e "${YELLOW}⚠️  Avatar URL didn't change${NC}"
  fi
else
  echo -e "${RED}❌ User update failed or avatar not in response${NC}"
fi
echo ""

# 6. Verify avatar file exists
echo "6️⃣ Verifying avatar file exists..."
if echo "$UPDATE_RESPONSE" | jq -e '.user.avatar' > /dev/null 2>&1; then
  AVATAR_PATH=$(echo "$UPDATE_RESPONSE" | jq -r '.user.avatar')
  FULL_PATH="./uploads/avatars/$(basename $AVATAR_PATH)"

  if [ -f "$FULL_PATH" ]; then
    echo -e "${GREEN}✅ Avatar file exists on disk${NC}"
    ls -lh "$FULL_PATH"
  else
    echo -e "${RED}❌ Avatar file not found: $FULL_PATH${NC}"
  fi
else
  echo -e "${YELLOW}⚠️  Skipping file check - no avatar in response${NC}"
fi
echo ""

# 7. Test static file serving
echo "7️⃣ Testing static file serving..."
if echo "$UPDATE_RESPONSE" | jq -e '.user.avatar' > /dev/null 2>&1; then
  AVATAR_URL=$(echo "$UPDATE_RESPONSE" | jq -r '.user.avatar')
  STATIC_RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" "http://localhost:8080$AVATAR_URL")

  if [ "$STATIC_RESPONSE" = "200" ]; then
    echo -e "${GREEN}✅ Avatar accessible via HTTP${NC}"
    echo "URL: http://localhost:8080$AVATAR_URL"
  else
    echo -e "${RED}❌ Avatar not accessible (HTTP $STATIC_RESPONSE)${NC}"
  fi
else
  echo -e "${YELLOW}⚠️  Skipping static file test - no avatar URL${NC}"
fi
echo ""

# Cleanup
rm -f /tmp/test-avatar.png /tmp/test-avatar-2.png

echo ""
echo "================================"
echo "🎯 Test Summary"
echo "================================"
if echo "$UPDATE_RESPONSE" | jq -e '.user.avatar' > /dev/null 2>&1; then
  echo -e "${GREEN}✅ Avatar update is working!${NC}"
else
  echo -e "${RED}❌ Avatar update is NOT working${NC}"
  echo ""
  echo "Debug info:"
  echo "- User ID: $USER_ID"
  echo "- Content-Type was: multipart/form-data"
  echo "- Check server logs for errors"
fi
