#!/bin/bash
# ChatBud API Testing Script
# Prerequisites: 
# 1. Web server running on http://localhost:8000
# 2. Database configured and imported
# 3. Email service configured
# Usage: bash test_api.sh

API_URL="http://localhost:8000/api.php/v1"
TEST_EMAIL="testuser_$(date +%s)@chatbud.local"
TEST_USERNAME="testuser_$(date +%s)"
TEST_PASSWORD="TestPassword123"
COOKIES_FILE="cookies.txt"

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

echo "╔════════════════════════════════════════════╗"
echo "║    ChatBud API Testing Script              ║"
echo "╚════════════════════════════════════════════╝"
echo ""

# Test 1: Register User
echo -e "${YELLOW}Test 1: Registering new user...${NC}"
echo "Email: $TEST_EMAIL"
echo "Username: $TEST_USERNAME"
echo ""

REGISTER_RESPONSE=$(curl -s -X POST "$API_URL/auth/register" \
  -H "Content-Type: application/json" \
  -d "{
    \"email\": \"$TEST_EMAIL\",
    \"username\": \"$TEST_USERNAME\",
    \"password\": \"$TEST_PASSWORD\",
    \"display_name\": \"Test User\"
  }")

echo "Response: $REGISTER_RESPONSE"
echo ""

# Extract user ID from response
USER_ID=$(echo "$REGISTER_RESPONSE" | grep -o '"id":"[^"]*' | head -1 | cut -d'"' -f4)

if [ -z "$USER_ID" ]; then
  echo -e "${RED}✗ Registration failed${NC}"
  echo "Response: $REGISTER_RESPONSE"
  exit 1
fi

echo -e "${GREEN}✓ User registered: $USER_ID${NC}"
echo ""

# Test 2: Login
echo -e "${YELLOW}Test 2: Logging in...${NC}"
LOGIN_RESPONSE=$(curl -s -X POST "$API_URL/auth/login" \
  -H "Content-Type: application/json" \
  -c "$COOKIES_FILE" \
  -d "{
    \"email\": \"$TEST_EMAIL\",
    \"password\": \"$TEST_PASSWORD\"
  }")

echo "Response: $LOGIN_RESPONSE"
echo ""

if echo "$LOGIN_RESPONSE" | grep -q '"success":true'; then
  echo -e "${GREEN}✓ Login successful${NC}"
else
  echo -e "${RED}✗ Login failed${NC}"
  exit 1
fi
echo ""

# Test 3: Get Current User
echo -e "${YELLOW}Test 3: Getting current user profile...${NC}"
USER_RESPONSE=$(curl -s -X GET "$API_URL/users/$USER_ID" \
  -H "Content-Type: application/json")

echo "Response: $USER_RESPONSE"
echo ""

if echo "$USER_RESPONSE" | grep -q '"success":true'; then
  echo -e "${GREEN}✓ Got user profile${NC}"
else
  echo -e "${RED}✗ Failed to get user profile${NC}"
fi
echo ""

# Test 4: Create a Post
echo -e "${YELLOW}Test 4: Creating a post...${NC}"
POST_RESPONSE=$(curl -s -X POST "$API_URL/posts" \
  -H "Content-Type: application/json" \
  -b "$COOKIES_FILE" \
  -d '{
    "content": "Hello, ChatBud! 🎉 This is my first post!"
  }')

echo "Response: $POST_RESPONSE"
echo ""

POST_ID=$(echo "$POST_RESPONSE" | grep -o '"id":"[^"]*' | head -1 | cut -d'"' -f4)

if [ ! -z "$POST_ID" ]; then
  echo -e "${GREEN}✓ Post created: $POST_ID${NC}"
else
  echo -e "${RED}✗ Failed to create post${NC}"
  echo "Response: $POST_RESPONSE"
fi
echo ""

# Test 5: Get the Post
if [ ! -z "$POST_ID" ]; then
  echo -e "${YELLOW}Test 5: Getting the post...${NC}"
  GET_POST_RESPONSE=$(curl -s -X GET "$API_URL/posts/$POST_ID" \
    -H "Content-Type: application/json")
  
  echo "Response: $GET_POST_RESPONSE"
  echo ""
  
  if echo "$GET_POST_RESPONSE" | grep -q '"success":true'; then
    echo -e "${GREEN}✓ Got post${NC}"
  else
    echo -e "${RED}✗ Failed to get post${NC}"
  fi
  echo ""
fi

# Test 6: Like a Post
if [ ! -z "$POST_ID" ]; then
  echo -e "${YELLOW}Test 6: Liking the post...${NC}"
  LIKE_RESPONSE=$(curl -s -X POST "$API_URL/posts/$POST_ID/like" \
    -H "Content-Type: application/json" \
    -b "$COOKIES_FILE")
  
  echo "Response: $LIKE_RESPONSE"
  echo ""
  
  if echo "$LIKE_RESPONSE" | grep -q '"success":true'; then
    echo -e "${GREEN}✓ Post liked${NC}"
  else
    echo -e "${RED}✗ Failed to like post${NC}"
  fi
  echo ""
fi

# Test 7: Add a Comment
if [ ! -z "$POST_ID" ]; then
  echo -e "${YELLOW}Test 7: Adding a comment...${NC}"
  COMMENT_RESPONSE=$(curl -s -X POST "$API_URL/posts/$POST_ID/comments" \
    -H "Content-Type: application/json" \
    -b "$COOKIES_FILE" \
    -d '{
      "content": "Great post! Love ChatBud 💬"
    }')
  
  echo "Response: $COMMENT_RESPONSE"
  echo ""
  
  if echo "$COMMENT_RESPONSE" | grep -q '"success":true'; then
    echo -e "${GREEN}✓ Comment added${NC}"
  else
    echo -e "${RED}✗ Failed to add comment${NC}"
  fi
  echo ""
fi

# Test 8: Get Posts (Feed)
echo -e "${YELLOW}Test 8: Getting feed...${NC}"
FEED_RESPONSE=$(curl -s -X GET "$API_URL/feed?limit=10" \
  -H "Content-Type: application/json" \
  -b "$COOKIES_FILE")

echo "Response (truncated): $(echo "$FEED_RESPONSE" | cut -c 1-200)..."
echo ""

if echo "$FEED_RESPONSE" | grep -q '"success":true'; then
  echo -e "${GREEN}✓ Got feed${NC}"
else
  echo -e "${RED}✗ Failed to get feed${NC}"
fi
echo ""

# Test 9: Update Profile
echo -e "${YELLOW}Test 9: Updating user profile...${NC}"
UPDATE_RESPONSE=$(curl -s -X PUT "$API_URL/users/$USER_ID" \
  -H "Content-Type: application/json" \
  -b "$COOKIES_FILE" \
  -d '{
    "display_name": "Test User Updated",
    "bio": "I love ChatBud!"
  }')

echo "Response: $UPDATE_RESPONSE"
echo ""

if echo "$UPDATE_RESPONSE" | grep -q '"success":true'; then
  echo -e "${GREEN}✓ Profile updated${NC}"
else
  echo -e "${RED}✗ Failed to update profile${NC}"
fi
echo ""

# Test 10: Logout
echo -e "${YELLOW}Test 10: Logging out...${NC}"
LOGOUT_RESPONSE=$(curl -s -X POST "$API_URL/auth/logout" \
  -H "Content-Type: application/json" \
  -b "$COOKIES_FILE")

echo "Response: $LOGOUT_RESPONSE"
echo ""

if echo "$LOGOUT_RESPONSE" | grep -q '"success":true'; then
  echo -e "${GREEN}✓ Logged out successfully${NC}"
else
  echo -e "${RED}✗ Logout failed${NC}"
fi
echo ""

# Cleanup
rm -f "$COOKIES_FILE"

echo "╔════════════════════════════════════════════╗"
echo "║    API Testing Complete! ✓                 ║"
echo "╚════════════════════════════════════════════╝"
echo ""
echo "Summary:"
echo "- Registered user: $USER_ID"
echo "- Created post: $POST_ID"
echo "- Tested authentication"
echo "- Tested CRUD operations"
echo ""
echo "See API_DOCUMENTATION.md for complete endpoint documentation"
