#!/bin/bash

# delete_test.sh - Test script for DELETE /<sha256> endpoint (BUD-02)
# This script tests the blob deletion functionality

set -e  # Exit on any error

# Configuration
SERVER_URL="http://localhost:9001"
TEST_FILE="test_delete_blob_$(date +%s).txt"
CLEANUP_FILES=()

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

# Cleanup function
cleanup() {
    echo -e "${YELLOW}Cleaning up temporary files...${NC}"
    for file in "${CLEANUP_FILES[@]}"; do
        if [[ -f "$file" ]]; then
            rm -f "$file"
            echo "Removed: $file"
        fi
    done
}

# Set up cleanup on exit
trap cleanup EXIT

# Helper functions
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Create test file and upload it first
create_and_upload_blob() {
    log_info "Creating test file for deletion: ${TEST_FILE}"
    
    # Create test content
    cat > "${TEST_FILE}" << EOF
Test blob for deletion
Timestamp: $(date -Iseconds)
Random: $(openssl rand -hex 16)
This file will be deleted as part of the DELETE test.
EOF
    
    CLEANUP_FILES+=("${TEST_FILE}")
    
    # Calculate hash
    HASH=$(sha256sum "${TEST_FILE}" | cut -d' ' -f1)
    log_success "File hash: ${HASH}"
    
    # Generate upload event
    EXPIRATION=$(date -d '+1 hour' +%s)
    UPLOAD_EVENT=$(nak event -k 24242 -c "" \
        -t "t=upload" \
        -t "x=${HASH}" \
        -t "expiration=${EXPIRATION}")
    
    # DEBUG: Print the upload event details
    echo "=== UPLOAD EVENT DEBUG ==="
    echo "Upload event JSON:"
    echo "$UPLOAD_EVENT" | jq '.'
    UPLOAD_PUBKEY=$(echo "$UPLOAD_EVENT" | jq -r '.pubkey')
    echo "Upload pubkey: $UPLOAD_PUBKEY"
    echo "=========================="
    
    # Upload the file
    UPLOAD_AUTH=$(echo -n "$UPLOAD_EVENT" | base64 -w 0)
    
    log_info "Uploading blob first..."
    HTTP_STATUS=$(curl -s -w "%{http_code}" \
        -X PUT \
        -H "Authorization: Nostr ${UPLOAD_AUTH}" \
        -H "Content-Type: text/plain" \
        --data-binary "@${TEST_FILE}" \
        "${SERVER_URL}/upload" \
        -o /dev/null)
    
    if [[ "$HTTP_STATUS" == "200" ]]; then
        log_success "Upload successful (HTTP $HTTP_STATUS)"
    else
        log_error "Upload failed (HTTP $HTTP_STATUS)"
        exit 1
    fi
    
    # Verify file exists
    if curl -s -f "${SERVER_URL}/${HASH}.txt" > /dev/null; then
        log_success "File confirmed accessible at /${HASH}.txt"
    else
        log_error "Uploaded file not accessible"
        exit 1
    fi
}

# Test DELETE with authorization
test_delete_with_auth() {
    log_info "Testing DELETE /${HASH} with proper authorization..."
    
    # Generate delete event
    EXPIRATION=$(date -d '+1 hour' +%s)
    DELETE_EVENT=$(nak event -k 24242 -c "" \
        -t "t=delete" \
        -t "x=${HASH}" \
        -t "expiration=${EXPIRATION}")
    
    # DEBUG: Print the delete event details
    echo "=== DELETE EVENT DEBUG ==="
    echo "Delete event JSON:"
    echo "$DELETE_EVENT" | jq '.'
    DELETE_PUBKEY=$(echo "$DELETE_EVENT" | jq -r '.pubkey')
    echo "Delete pubkey: $DELETE_PUBKEY"
    echo "Upload pubkey: $UPLOAD_PUBKEY"
    if [[ "$UPLOAD_PUBKEY" == "$DELETE_PUBKEY" ]]; then
        echo "✓ Pubkeys MATCH"
    else
        echo "✗ Pubkeys DIFFER - This is the problem!"
    fi
    echo "=========================="
    
    DELETE_AUTH=$(echo -n "$DELETE_EVENT" | base64 -w 0)
    
    # Perform DELETE request
    RESPONSE_FILE=$(mktemp)
    CLEANUP_FILES+=("${RESPONSE_FILE}")
    
    HTTP_STATUS=$(curl -s -w "%{http_code}" \
        -X DELETE \
        -H "Authorization: Nostr ${DELETE_AUTH}" \
        "${SERVER_URL}/${HASH}" \
        -o "${RESPONSE_FILE}")
    
    echo "HTTP Status: ${HTTP_STATUS}"
    echo "Response body:"
    cat "${RESPONSE_FILE}"
    echo
    
    case "${HTTP_STATUS}" in
        200)
            log_success "Delete successful!"
            ;;
        401)
            log_error "Unauthorized - check authorization"
            ;;
        403)
            log_error "Forbidden - ownership check failed"
            ;;
        404)
            log_error "Not found - blob doesn't exist"
            ;;
        *)
            log_error "Delete failed with HTTP status: ${HTTP_STATUS}"
            ;;
    esac
}

# Test that file is actually deleted
test_file_deletion() {
    log_info "Verifying file is actually deleted..."
    
    # Try to access the file
    if curl -s -f "${SERVER_URL}/${HASH}.txt" > /dev/null 2>&1; then
        log_error "File still accessible after deletion!"
    else
        log_success "File correctly deleted from server"
    fi
    
    # Try HEAD request
    HEAD_STATUS=$(curl -s -w "%{http_code}" -I "${SERVER_URL}/${HASH}" -o /dev/null)
    if [[ "$HEAD_STATUS" == "404" ]]; then
        log_success "HEAD request correctly returns 404"
    else
        log_error "HEAD request returned ${HEAD_STATUS}, expected 404"
    fi
}

# Main execution
main() {
    echo "=== Ginxsom DELETE Test (BUD-02) ==="
    echo "Timestamp: $(date -Iseconds)"
    echo
    
    create_and_upload_blob
    echo
    test_delete_with_auth
    echo
    test_file_deletion
    echo

    
    log_info "DELETE test completed!"
    echo "Summary:"
    echo "  Test hash: ${HASH}"
    echo "  Server: ${SERVER_URL}"
    echo "  DELETE endpoint tested: ${SERVER_URL}/<sha256>"
}

# Run main function
main "$@"
