#!/bin/bash

# Mirror Test Script for BUD-04
# Tests the PUT /mirror endpoint with a sample PNG file

# Test URL - PNG file with known SHA-256 hash
TEST_URL="https://laantungir.github.io/img_repo/24308d48eb498b593e55a87b6300ccffdea8432babc0bb898b1eff21ebbb72de.png"
EXPECTED_HASH="24308d48eb498b593e55a87b6300ccffdea8432babc0bb898b1eff21ebbb72de"

echo "=== BUD-04 Mirror Endpoint Test ==="
echo "Target URL: $TEST_URL"
echo "Expected Hash: $EXPECTED_HASH"
echo ""

# Create JSON request body
JSON_BODY=$(cat <<EOF
{
  "url": "$TEST_URL"
}
EOF
)

echo "Request Body:"
echo "$JSON_BODY"
echo ""

# Make the mirror request
echo "=== Making Mirror Request ==="
RESPONSE=$(curl -s -w "\nHTTP_CODE:%{http_code}\n" \
  -X PUT \
  -H "Content-Type: application/json" \
  -d "$JSON_BODY" \
  http://localhost:9001/mirror)

echo "Response:"
echo "$RESPONSE"
echo ""

# Extract HTTP status code
HTTP_CODE=$(echo "$RESPONSE" | grep "HTTP_CODE:" | cut -d: -f2)
echo "HTTP Status Code: $HTTP_CODE"

# Check if successful
if [ "$HTTP_CODE" = "200" ]; then
    echo "✅ Mirror request successful!"
    
    # Try to access the mirrored blob
    echo ""
    echo "=== Verifying Mirrored Blob ==="
    echo "Attempting to fetch: http://localhost:9001/$EXPECTED_HASH.png"
    
    BLOB_RESPONSE=$(curl -s -w "HTTP_CODE:%{http_code}" -I "http://localhost:9001/$EXPECTED_HASH.png")
    BLOB_HTTP_CODE=$(echo "$BLOB_RESPONSE" | grep "HTTP_CODE:" | cut -d: -f2)
    
    if [ "$BLOB_HTTP_CODE" = "200" ]; then
        echo "✅ Mirrored blob accessible!"
        echo ""
        echo "=== Blob Headers ==="
        echo "$BLOB_RESPONSE" | grep -v "HTTP_CODE:"
    else
        echo "❌ Mirrored blob not accessible (HTTP $BLOB_HTTP_CODE)"
    fi
    
    # Test HEAD request for metadata
    echo ""
    echo "=== Testing HEAD Request ==="
    HEAD_RESPONSE=$(curl -s -w "HTTP_CODE:%{http_code}" -I -X HEAD "http://localhost:9001/$EXPECTED_HASH")
    HEAD_HTTP_CODE=$(echo "$HEAD_RESPONSE" | grep "HTTP_CODE:" | cut -d: -f2)
    
    if [ "$HEAD_HTTP_CODE" = "200" ]; then
        echo "✅ HEAD request successful!"
        echo "Metadata headers:"
        echo "$HEAD_RESPONSE" | grep -E "(Content-Type|Content-Length|ETag)" | grep -v "HTTP_CODE:"
    else
        echo "❌ HEAD request failed (HTTP $HEAD_HTTP_CODE)"
    fi
    
else
    echo "❌ Mirror request failed (HTTP $HTTP_CODE)"
    if [ "$HTTP_CODE" != "000" ]; then
        echo "Response body:"
        echo "$RESPONSE" | grep -v "HTTP_CODE:"
    fi
fi

echo ""
echo "=== Test Complete ==="