#!/bin/bash

# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

BASE_URL="http://localhost:8000/api/v1"
ACCESS_TOKEN=""
SUPERADMIN_ID=""

# Print response as JSON if valid, otherwise show raw (e.g. PHP warnings)
# Uses sed instead of head for portability (some systems have head = HTTP client)
print_response() {
  local body="$1"
  local trimmed
  trimmed=$(echo "$body" | sed 's/^[[:space:]]*//')
  local first_char="${trimmed:0:1}"
  if [ "$first_char" = "{" ] || [ "$first_char" = "[" ]; then
    echo "$body" | json_pp 2>/dev/null || echo "$body"
  else
    echo -e "${RED}(Response is not JSON - possible server error)${NC}"
    echo "$body" | sed -n '1,20p'
  fi
}

echo -e "${BLUE}=== SalesUI SuperAdmin API Test Suite ===${NC}\n"

# 1. LOGIN
echo -e "${GREEN}1. Logging in as Super Admin...${NC}"
LOGIN_RESPONSE=$(curl -s --request POST "$BASE_URL/superadmin/login" \
  --header 'Content-Type: application/json' \
  --header 'Accept: application/json' \
  --data-raw '{
    "email": "john.doe@example.com",
    "password": "password123"
  }')

ACCESS_TOKEN=$(echo $LOGIN_RESPONSE | grep -o '"access_token":"[^"]*' | cut -d'"' -f4)

echo -e "✓ Login successful"
echo -e "  Access Token: ${ACCESS_TOKEN:0:50}...\n"

# 2. GET PROFILE (and capture ID for use if create fails)
echo -e "${GREEN}2. Getting profile...${NC}"
PROFILE_RESPONSE=$(curl -s --request GET "$BASE_URL/superadmin/profile" \
  --header "Authorization: Bearer $ACCESS_TOKEN" \
  --header 'Accept: application/json')
print_response "$PROFILE_RESPONSE"
PROFILE_ID=$(echo "$PROFILE_RESPONSE" | grep -o '"id":"[^"]*' | cut -d'"' -f4)

echo -e "\n"

# 3. CREATE SUPERADMIN WITH IMAGE
echo -e "${GREEN}3. Creating new SuperAdmin with image...${NC}"

# Create a minimal valid test image if it doesn't exist (1x1 pixel JPEG, base64)
if [ ! -f "./test-image.jpg" ]; then
  echo "Creating test image..."
  echo '/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAv/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBEQACEQAD/AD/2Q==' | base64 -d > ./test-image.jpg 2>/dev/null || true
fi

if [ -f "./test-image.jpg" ] && [ -s "./test-image.jpg" ]; then
  CREATE_RESPONSE=$(curl -s --request POST "$BASE_URL/superadmins" \
    --header "Authorization: Bearer $ACCESS_TOKEN" \
    --header 'Accept: application/json' \
    --form 'first_name="Test"' \
    --form 'last_name="User"' \
    --form 'email="testing.user@example.com"' \
    --form 'password="password123"' \
    --form 'image=@"./test-image.jpg"')
else
  # No image file: create with JSON only so we get a valid ID for update/delete
  CREATE_RESPONSE=$(curl -s --request POST "$BASE_URL/superadmins" \
    --header "Authorization: Bearer $ACCESS_TOKEN" \
    --header 'Content-Type: application/json' \
    --header 'Accept: application/json' \
    --data-raw '{
      "first_name": "Test",
      "last_name": "User",
      "email": "testing.user@example.com",
      "password": "password123"
    }')
fi

SUPERADMIN_ID=$(echo "$CREATE_RESPONSE" | grep -o '"id":"[^"]*' | cut -d'"' -f4)
IMAGE_URL=$(echo "$CREATE_RESPONSE" | grep -o '"image_url":"[^"]*' | cut -d'"' -f4)
# If create failed (e.g. duplicate email), use profile id so update/delete still hit the correct route
if [ -z "$SUPERADMIN_ID" ]; then
  SUPERADMIN_ID="$PROFILE_ID"
  echo -e "✓ Create returned no ID (may already exist), using profile ID for update/delete: $SUPERADMIN_ID"
else
  echo -e "✓ Created SuperAdmin with ID: $SUPERADMIN_ID"
fi
echo -e "  Image URL: $IMAGE_URL\n"

# 4. GET ALL SUPERADMINS
echo -e "${GREEN}4. Getting all SuperAdmins...${NC}"
print_response "$(curl -s --request GET "$BASE_URL/superadmins?page=1&per_page=5" \
  --header "Authorization: Bearer $ACCESS_TOKEN" \
  --header 'Accept: application/json')"

echo -e "\n"

# 5. GET SINGLE SUPERADMIN
echo -e "${GREEN}5. Getting SuperAdmin by ID...${NC}"
print_response "$(curl -s --request GET "$BASE_URL/superadmins/$SUPERADMIN_ID" \
  --header "Authorization: Bearer $ACCESS_TOKEN" \
  --header 'Accept: application/json')"

echo -e "\n"

# 6. UPDATE SUPERADMIN
echo -e "${GREEN}6. Updating SuperAdmin...${NC}"
print_response "$(curl -s --request PUT "$BASE_URL/superadmins/$SUPERADMIN_ID" \
  --header "Authorization: Bearer $ACCESS_TOKEN" \
  --header 'Content-Type: application/json' \
  --header 'Accept: application/json' \
  --data-raw '{
    "first_name": "Updated Test",
    "last_name": "Updated User"
  }')"

echo -e "\n"

# 7. SEARCH SUPERADMINS
echo -e "${GREEN}7. Searching SuperAdmins...${NC}"
print_response "$(curl -s --request GET "$BASE_URL/superadmins?search=Updated&page=1" \
  --header "Authorization: Bearer $ACCESS_TOKEN" \
  --header 'Accept: application/json')"

echo -e "\n"

# 8. REMOVE IMAGE
echo -e "${GREEN}8. Removing image from SuperAdmin...${NC}"
print_response "$(curl -s --request PUT "$BASE_URL/superadmins/$SUPERADMIN_ID" \
  --header "Authorization: Bearer $ACCESS_TOKEN" \
  --header 'Content-Type: application/json' \
  --header 'Accept: application/json' \
  --data-raw '{
    "remove_image": true
  }')"

echo -e "\n"

# 9. DELETE SUPERADMIN (skip if we used profile id - don't delete current user)
echo -e "${GREEN}9. Deleting SuperAdmin...${NC}"
if [ "$SUPERADMIN_ID" = "$PROFILE_ID" ]; then
  echo -e "  Skipped (using profile ID; would delete current user)\n"
else
  print_response "$(curl -s --request DELETE "$BASE_URL/superadmins/$SUPERADMIN_ID" \
    --header "Authorization: Bearer $ACCESS_TOKEN" \
    --header 'Accept: application/json')"
fi

echo -e "\n"

# 10. LOGOUT
echo -e "${GREEN}10. Logging out...${NC}"
print_response "$(curl -s --request POST "$BASE_URL/superadmin/logout" \
  --header "Authorization: Bearer $ACCESS_TOKEN" \
  --header 'Accept: application/json')"

echo -e "\n${BLUE}=== Test Suite Completed ===${NC}"
