#!/bin/bash

# API base URL
API_BASE_URL="http://10.0.0.16:8080"

# Login credentials
USERNAME="boxuser"
PASSWORD="boxuser"

# Function to make an authenticated request
function authenticated_request() {
  local method=$1
  local endpoint=$2
  local data=$3

  # Get a new JWT token
  TOKEN=$(curl -s -X POST -H "Content-Type: application/json" \
    -d "{\"username\":\"$USERNAME\", \"password\":\"$PASSWORD\"}" \
    "$API_BASE_URL/login" | jq -r '.token')

  # Make the authenticated request
  curl -s -X $method -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d "$data" \
    "$API_BASE_URL$endpoint"
}

# --- Test Cases ---

# 1. Login
echo
echo
echo "Testing /login..."
response=$(curl -s -w "%{http_code}" -X POST -H "Content-Type: application/json" \
  -d "{\"username\":\"$USERNAME\", \"password\":\"$PASSWORD\"}" \
  "$API_BASE_URL/login")

# Separate the body and the HTTP status code
http_status=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')

# Print response body for debugging
echo "$body" | jq .

# Check if the HTTP status is 200 (OK) and the token is not null
if [[ "$http_status" == "200" && $(echo "$body" | jq -r '.token') != "null" ]]; then
  echo -e "\033[32m  /login: PASS\033[0m" # Green PASS
else
  echo -e "\033[31m  /login: FAIL (Invalid response or no token)\033[0m" # Red FAIL
  echo "$response"
fi

# 2. Get Boxes
echo
echo
echo "Testing /boxes (GET)..."
response=$(authenticated_request "GET" "/boxes" "")

# Directly check the curl exit code for success (0)
if [[ $? -eq 0 ]]; then
  echo -e "\033[32m  /boxes (GET): PASS\033[0m" # Green PASS
else
  echo -e "\033[31m  /boxes (GET): FAIL (Request failed)\033[0m" # Red FAIL
  echo "Response: $response" # Print the response in case of error
fi

# 3. Create Box
echo
echo
echo "Testing /boxes (POST)..."
response=$(authenticated_request "POST" "/boxes" "{\"name\":\"Test Box\"}")
echo $response | jq '.'

if [[ $(echo "$response" | jq -r '.name') == "Test Box" ]]; then
  echo -e "\033[32m  /boxes (POST): PASS\033[0m" # Green PASS
  echo $response
  BOX_ID=$(echo "$response" | jq -r '.id') # Extract and save the box ID
  echo $BOX_ID | jq .
else
  echo -e "\033[31m  /boxes (POST): FAIL (Invalid response)\033[0m" # Red FAIL
  echo "$response"
fi

# 2. Get Boxes again to make sure one is created
echo
echo
echo "Testing /boxes (GET) again to verify creation..."
response=$(authenticated_request "GET" "/boxes" "")

# Check the curl exit code for success (0) AND if a box with $BOX_ID exists
if [[ $? -eq 0 ]] && jq -e '.[] | select(.ID == '$BOX_ID')' <<< "$response" > /dev/null 2>&1; then
  echo -e "\033[32m  /boxes (GET): PASS\033[0m" # Green PASS
else
  echo -e "\033[31m  /boxes (GET): FAIL (Request failed or box not found)\033[0m" # Red FAIL
  echo "Response: $response" # Print the response in case of error
fi

# 5. Create Item (Assuming a box with ID $BOX_ID exists)
echo
echo
echo "Testing /items (POST)..."
echo $BOX_ID
response=$(authenticated_request "POST" "/items" "{\"name\":\"Test Item\", \"description\":\"Test Description\", \"box_id\":$BOX_ID}")
if [[ $(echo "$response" | jq -r '.name') == "Test Item" ]]; then
  echo -e "\033[32m  /items (POST): PASS\033[0m" # Green PASS
  ITEM_ID=$(echo "$response" | jq -r '.id') # Extract and save the item ID
  echo $response
else
  echo -e "\033[31m  /items (POST): FAIL (Invalid response)\033[0m" # Red FAIL
  echo "$response"
fi

# 11. Create Image and Assign to Item (Assuming an item with ID $ITEM_ID exists)
echo
echo
echo "Testing /items/$ITEM_ID/upload (POST)..."

# Get a new JWT token
TOKEN=$(curl -s -X POST -H "Content-Type: application/json" \
  -d "{\"username\":\"$USERNAME\", \"password\":\"$PASSWORD\"}" \
  "$API_BASE_URL/login" | jq -r '.token')

# Create a temporary image file
IMAGE_FILE=$(mktemp /tmp/test_image.XXXXXX)
echo "Test Image Content" > "$IMAGE_FILE"

echo "Token is $TOKEN"

# Make the request using curl to upload the image
response=$(curl -s -w "%{http_code}" -X POST \
  -H "Authorization: Bearer $(echo "$TOKEN")" \
  -F "image=@$IMAGE_FILE" \
  "$API_BASE_URL/items/$ITEM_ID/upload")

echo $response 

# Separate the body and the HTTP status code
http_status=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')

# Remove the temporary image file
rm "$IMAGE_FILE"

# Check if the HTTP status is 200 (OK) and the imagePath is returned
if [[ "$http_status" == "200" && $(echo "$body" | jq -r '.imagePath') != "null" ]]; then
  echo -e "\033[32m  /items/$ITEM_ID/upload (POST): PASS\033[0m" # Green PASS
  IMAGE_PATH=$(echo "$body" | jq -r '.imagePath')
  echo "Image Path: $IMAGE_PATH"
else
  echo -e "\033[31m  /items/$ITEM_ID/upload (POST): FAIL (Invalid response or no imagePath)\033[0m" # Red FAIL
  echo "Response: $response"
fi


# 6. Get Items
echo
echo "Testing /items (GET)..."
response=$(authenticated_request "GET" "/items" "")
echo 

# Check if the request was successful AND if an item with $ITEM_ID exists
if [[ $? -eq 0 ]] && jq -e '.[] | select(.ID == '$ITEM_ID')' <<< "$response" > /dev/null 2>&1; then
  echo -e "\033[32m  /items (GET): PASS\033[0m" # Green PASS
else
  echo -e "\033[31m  /items (GET): FAIL (Request failed or item not found)\033[0m" # Red FAIL
  echo "Response: $response" # Print the response in case of error
fi

# 7. Get Item by ID (Using the saved ITEM_ID)
echo
echo
echo "Testing /items/{id} (GET)..."
response=$(authenticated_request "GET" "/items/$ITEM_ID" "")

echo $response | jq .

# Check if the request was successful AND if the response ID matches $ITEM_ID
if [[ $? -eq 0 ]] && [[ $(echo "$response" | jq -r '.ID') == "$ITEM_ID" ]]; then
  echo -e "\033[32m  /items/{id} (GET): PASS\033[0m" # Green PASS
else
  echo -e "\033[31m  /items/{id} (GET): FAIL (Request failed or ID mismatch)\033[0m" # Red FAIL
  echo "Response: $response" # Print the response in case of error
fi

# 8. Get Items in Box (Using the saved BOX_ID)
echo
echo
echo "Testing /items/{id}/items (GET)..."
echo "Box ID: $BOX_ID"
response=$(authenticated_request "GET" "/items/$BOX_ID/items")
echo "$response"

if [[ $(echo "$response" | jq -r '. | length') -ge 1 ]]; then # Expecting at least one item
  echo -e "\033[32m  /items/{id}/items (GET): PASS\033[0m" # Green PASS
else
  echo -e "\033[31m  /items/{id}/items (GET): FAIL (Invalid response)\033[0m" # Red FAIL
  echo "$response"
fi

# 9. Update Item (Using the saved ITEM_ID)
echo
echo
echo "Testing /items/{id} (PUT)..."
response=$(authenticated_request "PUT" "/items/$ITEM_ID" "{\"name\":\"Updated Item\", \"description\":\"Updated Description\"}")

if [[ $(echo "$response" | jq -r '.name') == "Updated Item" ]]; then
  echo -e "\033[32m  /items/{id} (PUT): PASS\033[0m" # Green PASS
else
  echo -e "\033[31m  /items/{id} (PUT): FAIL (Invalid response)\033[0m" # Red FAIL
  echo "$response"
fi

# 10. Delete Item (Using the saved ITEM_ID)
echo
echo
echo "Testing /items/{id} (DELETE)..."
response=$(authenticated_request "DELETE" "/items/$ITEM_ID" "")

# Directly check the curl exit code for success (0)
if [[ $? -eq 0 ]]; then
  echo -e "\033[32m  /items/{id} (DELETE): PASS\033[0m" # Green PASS
else
  echo -e "\033[31m  /items/{id} (DELETE): FAIL (Request failed)\033[0m" # Red FAIL
  echo "Response: $response" # Print the response in case of error
fi

# 4. Delete Box (Using the saved BOX_ID)
echo
echo
echo "Testing /boxes/{id} (DELETE)..."
echo "BOX_ID: $BOX_ID"
response=$(authenticated_request "DELETE" "/boxes/$BOX_ID" "")

# Directly check the curl exit code for success (0)
if [[ $? -eq 0 ]]; then
  echo -e "\033[32m  /boxes/{id} (DELETE): PASS\033[0m" # Green PASS
else
  echo -e "\033[31m  /boxes/{id} (DELETE): FAIL (Request failed)\033[0m" # Red FAIL
  echo "Response: $response" # Print the response in case of error
fi

# --- Add more test cases for other endpoints ---

# Example for GET /items/{id}
# echo "Testing /items/{id} (GET)..."
# response=$(authenticated_request "GET" "/items/1" "")
# # ... (Add assertions based on the expected response)

echo "Tests completed."
