#!/bin/bash

echo "🧪 Testing User Create & Update with Avatar"
echo ""

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

# 1. Login as admin
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}1️⃣  Admin Login${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

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. Create test avatars
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}2️⃣  Creating Test Images${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

# Red pixel PNG for create
echo "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==" | base64 -d > /tmp/create-avatar.png

# Blue pixel PNG for update
echo "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" | base64 -d > /tmp/update-avatar.png

echo -e "${GREEN}✅ Test images created${NC}"
ls -lh /tmp/*-avatar.png
echo ""

# 3. TEST: Create User with Avatar
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}3️⃣  TEST: Create User with Avatar${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

TIMESTAMP=$(date +%s)
TEST_EMAIL="testuser_${TIMESTAMP}@example.com"
TEST_USERNAME="testuser_${TIMESTAMP}"

echo "Creating user:"
echo "  Email: $TEST_EMAIL"
echo "  Username: $TEST_USERNAME"
echo "  Password: Test123!"
echo "  Roles: user"
echo "  Avatar: create-avatar.png"
echo ""

CREATE_RESPONSE=$(curl -s -X POST http://localhost:8080/v1/admin/users \
  -H "Authorization: Bearer $TOKEN" \
  -F "email=$TEST_EMAIL" \
  -F "password=Test123!" \
  -F "user_name=$TEST_USERNAME" \
  -F "email_verified=true" \
  -F "roles=user" \
  -F "avatar=@/tmp/create-avatar.png")

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

# Check if user was created
if echo "$CREATE_RESPONSE" | jq -e '.id' > /dev/null 2>&1; then
  CREATED_USER_ID=$(echo "$CREATE_RESPONSE" | jq -r '.id')
  CREATED_AVATAR=$(echo "$CREATE_RESPONSE" | jq -r '.avatar')

  echo -e "${GREEN}✅ User created successfully!${NC}"
  echo "   User ID: $CREATED_USER_ID"
  echo "   Avatar: $CREATED_AVATAR"

  # Check if avatar exists
  if [ ! -z "$CREATED_AVATAR" ] && [ "$CREATED_AVATAR" != "null" ]; then
    echo -e "${GREEN}✅ Avatar included in create!${NC}"

    # Check file on disk
    AVATAR_FILE="./uploads/avatars/$(basename $CREATED_AVATAR)"
    if [ -f "$AVATAR_FILE" ]; then
      echo -e "${GREEN}✅ Avatar file exists on disk${NC}"
      ls -lh "$AVATAR_FILE"
    else
      echo -e "${RED}❌ Avatar file not found: $AVATAR_FILE${NC}"
    fi
  else
    echo -e "${RED}❌ Avatar NOT included in create response${NC}"
  fi
else
  echo -e "${RED}❌ User creation failed!${NC}"
  if echo "$CREATE_RESPONSE" | jq -e '.error' > /dev/null 2>&1; then
    ERROR=$(echo "$CREATE_RESPONSE" | jq -r '.error')
    echo "   Error: $ERROR"
  fi
fi
echo ""

# 4. TEST: Update User with Avatar
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}4️⃣  TEST: Update User with Avatar${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

if [ ! -z "$CREATED_USER_ID" ]; then
  NEW_USERNAME="updated_${TIMESTAMP}"

  echo "Updating user:"
  echo "  User ID: $CREATED_USER_ID"
  echo "  New Username: $NEW_USERNAME"
  echo "  New Avatar: update-avatar.png"
  echo ""

  UPDATE_RESPONSE=$(curl -s -X PUT "http://localhost:8080/v1/admin/users/$CREATED_USER_ID" \
    -H "Authorization: Bearer $TOKEN" \
    -F "user_name=$NEW_USERNAME" \
    -F "avatar=@/tmp/update-avatar.png")

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

  # Check if update was successful
  if echo "$UPDATE_RESPONSE" | jq -e '.user' > /dev/null 2>&1; then
    UPDATED_AVATAR=$(echo "$UPDATE_RESPONSE" | jq -r '.user.avatar')
    UPDATED_USERNAME=$(echo "$UPDATE_RESPONSE" | jq -r '.user.username')

    echo -e "${GREEN}✅ User updated successfully!${NC}"
    echo "   Username: $UPDATED_USERNAME"
    echo "   Avatar: $UPDATED_AVATAR"

    # Check if avatar changed
    if [ "$UPDATED_AVATAR" != "$CREATED_AVATAR" ]; then
      echo -e "${GREEN}✅ Avatar URL changed!${NC}"
      echo "   Old: $CREATED_AVATAR"
      echo "   New: $UPDATED_AVATAR"

      # Check new file on disk
      NEW_AVATAR_FILE="./uploads/avatars/$(basename $UPDATED_AVATAR)"
      if [ -f "$NEW_AVATAR_FILE" ]; then
        echo -e "${GREEN}✅ New avatar file exists on disk${NC}"
        ls -lh "$NEW_AVATAR_FILE"
      else
        echo -e "${RED}❌ New avatar file not found: $NEW_AVATAR_FILE${NC}"
      fi

      # Check if old file was deleted
      if [ -f "$AVATAR_FILE" ]; then
        echo -e "${YELLOW}⚠️  Old avatar file still exists (should be deleted)${NC}"
      else
        echo -e "${GREEN}✅ Old avatar file was deleted${NC}"
      fi
    else
      echo -e "${RED}❌ Avatar URL didn't change!${NC}"
    fi

    # Check username changed
    if [ "$UPDATED_USERNAME" = "$NEW_USERNAME" ]; then
      echo -e "${GREEN}✅ Username updated correctly${NC}"
    else
      echo -e "${RED}❌ Username not updated!${NC}"
    fi
  else
    echo -e "${RED}❌ User update failed!${NC}"
    if echo "$UPDATE_RESPONSE" | jq -e '.error' > /dev/null 2>&1; then
      ERROR=$(echo "$UPDATE_RESPONSE" | jq -r '.error')
      echo "   Error: $ERROR"
    fi
  fi
else
  echo -e "${YELLOW}⚠️  Skipping update test (user creation failed)${NC}"
fi
echo ""

# 5. Verify via GET
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}5️⃣  Verify User via GET${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

if [ ! -z "$CREATED_USER_ID" ]; then
  GET_RESPONSE=$(curl -s -X GET "http://localhost:8080/v1/admin/users/$CREATED_USER_ID" \
    -H "Authorization: Bearer $TOKEN")

  echo "User details from GET:"
  echo "$GET_RESPONSE" | jq .
  echo ""

  GET_AVATAR=$(echo "$GET_RESPONSE" | jq -r '.avatar')
  GET_USERNAME=$(echo "$GET_RESPONSE" | jq -r '.username')

  if [ ! -z "$GET_AVATAR" ] && [ "$GET_AVATAR" != "null" ]; then
    echo -e "${GREEN}✅ Avatar persisted in database${NC}"
    echo "   Avatar URL: $GET_AVATAR"
  else
    echo -e "${RED}❌ Avatar not in database${NC}"
  fi

  if [ "$GET_USERNAME" = "$NEW_USERNAME" ]; then
    echo -e "${GREEN}✅ Username persisted correctly${NC}"
  fi
else
  echo -e "${YELLOW}⚠️  Skipping GET test (user creation failed)${NC}"
fi
echo ""

# 6. Test Static File Serving
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}6️⃣  Test Static File Serving${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

if [ ! -z "$UPDATED_AVATAR" ] && [ "$UPDATED_AVATAR" != "null" ]; then
  HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "http://localhost:8080$UPDATED_AVATAR")

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

# 7. Cleanup (optional)
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}7️⃣  Cleanup${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

rm -f /tmp/create-avatar.png /tmp/update-avatar.png
echo -e "${GREEN}✅ Temporary files cleaned${NC}"
echo ""

# Summary
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}📊 TEST SUMMARY${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

CREATE_SUCCESS=false
UPDATE_SUCCESS=false

if [ ! -z "$CREATED_USER_ID" ] && [ ! -z "$CREATED_AVATAR" ] && [ "$CREATED_AVATAR" != "null" ]; then
  CREATE_SUCCESS=true
fi

if [ ! -z "$UPDATED_AVATAR" ] && [ "$UPDATED_AVATAR" != "$CREATED_AVATAR" ]; then
  UPDATE_SUCCESS=true
fi

echo ""
echo "Test Results:"
echo ""
if [ "$CREATE_SUCCESS" = true ]; then
  echo -e "  ${GREEN}✅ User Create with Avatar: WORKING${NC}"
else
  echo -e "  ${RED}❌ User Create with Avatar: FAILED${NC}"
fi

if [ "$UPDATE_SUCCESS" = true ]; then
  echo -e "  ${GREEN}✅ User Update with Avatar: WORKING${NC}"
else
  echo -e "  ${RED}❌ User Update with Avatar: FAILED${NC}"
fi

echo ""

if [ "$CREATE_SUCCESS" = true ] && [ "$UPDATE_SUCCESS" = true ]; then
  echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo -e "${GREEN}🎉 ALL TESTS PASSED!${NC}"
  echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  exit 0
else
  echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo -e "${RED}⚠️  SOME TESTS FAILED${NC}"
  echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  exit 1
fi
