#!/bin/bash
# Merchant API Testing Script
# Simple bash version for quick testing of merchant APIs

set -e

# Configuration
API_TOKEN="${API_TOKEN:-your_token_here}"
BASE_URL="${BASE_URL:-https://api.mercurypay.com}"
PARTNER_ID="${PARTNER_ID:-PARTNER_001}"

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

# Logging functions
log() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

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

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

debug() {
    echo -e "${BLUE}[DEBUG]${NC} $1"
}

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

# Test function
test_endpoint() {
    local method=$1
    local endpoint=$2
    local data=$3
    local expected_status=$4
    local test_name=$5
    
    log "Testing: $test_name"
    debug "  $method $endpoint"
    
    if [ -n "$data" ]; then
        response=$(curl -s -w "\n%{http_code}" -X "$method" \
            "$BASE_URL$endpoint" \
            -H "Authorization: Bearer $API_TOKEN" \
            -H "Content-Type: application/json" \
            -d "$data")
    else
        response=$(curl -s -w "\n%{http_code}" -X "$method" \
            "$BASE_URL$endpoint" \
            -H "Authorization: Bearer $API_TOKEN")
    fi
    
    status_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | head -n -1)
    
    if [ "$status_code" -eq "$expected_status" ]; then
        success "✓ $test_name (Status: $status_code)"
        if command -v jq >/dev/null 2>&1; then
            echo "$body" | jq . 2>/dev/null || echo "$body"
        else
            echo "$body"
        fi
        return 0
    else
        error "✗ $test_name (Expected: $expected_status, Got: $status_code)"
        echo "$body"
        return 1
    fi
}

# Extract value from JSON response
extract_json_value() {
    local json="$1"
    local key="$2"
    
    if command -v jq >/dev/null 2>&1; then
        echo "$json" | jq -r "$key" 2>/dev/null || echo ""
    else
        # Simple grep-based extraction for systems without jq
        echo "$json" | grep -o "\"$key\":[^,}]*" | cut -d: -f2 | tr -d '"' | tr -d ' '
    fi
}

# Test data templates
get_merchant_template() {
    local type=$1
    local timestamp=$(date +%s)
    
    case $type in
        "retail")
            echo '{
                "merchant_code": "RETAIL'$timestamp'",
                "brand_name": "Test Retail Store",
                "merchant_vpa": "retail'$timestamp'@upi",
                "business_type": "RETAIL",
                "corridors": ["DOMESTIC"],
                "contact_email": "test@retail.com",
                "contact_phone": "+91-9876543210"
            }'
            ;;
        "restaurant")
            echo '{
                "merchant_code": "REST'$timestamp'",
                "brand_name": "Test Restaurant",
                "merchant_vpa": "restaurant'$timestamp'@upi",
                "business_type": "FOOD_AND_BEVERAGE",
                "corridors": ["DOMESTIC"],
                "contact_email": "test@restaurant.com",
                "contact_phone": "+91-9876543211"
            }'
            ;;
        "international")
            echo '{
                "merchant_code": "INTL'$timestamp'",
                "brand_name": "Test International Corp",
                "merchant_vpa": "intl'$timestamp'@upi",
                "business_type": "IMPORT_EXPORT",
                "corridors": ["SGD-INR", "USD-INR"],
                "contact_email": "test@international.com",
                "contact_phone": "+91-9876543212",
                "fbar_number": "FBAR'$timestamp'"
            }'
            ;;
        *)
            echo '{
                "merchant_code": "TEST'$timestamp'",
                "brand_name": "Test Store",
                "merchant_vpa": "test'$timestamp'@upi",
                "business_type": "RETAIL",
                "corridors": ["DOMESTIC"],
                "contact_email": "test@store.com"
            }'
            ;;
    esac
}

# Main testing functions
test_merchant_creation() {
    log "=== TESTING MERCHANT CREATION ==="
    
    local retail_data=$(get_merchant_template "retail")
    local restaurant_data=$(get_merchant_template "restaurant")
    local international_data=$(get_merchant_template "international")
    
    # Test retail merchant creation
    response=$(test_endpoint "POST" "/api/v1/partners/$PARTNER_ID/merchants" \
        "$retail_data" 201 "Create Retail Merchant")
    
    if [ $? -eq 0 ]; then
        RETAIL_MERCHANT_ID=$(extract_json_value "$response" ".data.id")
        if [ -n "$RETAIL_MERCHANT_ID" ] && [ "$RETAIL_MERCHANT_ID" != "null" ]; then
            success "Retail merchant created with ID: $RETAIL_MERCHANT_ID"
        fi
    fi
    
    # Test restaurant merchant creation
    response=$(test_endpoint "POST" "/api/v1/partners/$PARTNER_ID/merchants" \
        "$restaurant_data" 201 "Create Restaurant Merchant")
    
    if [ $? -eq 0 ]; then
        RESTAURANT_MERCHANT_ID=$(extract_json_value "$response" ".data.id")
        if [ -n "$RESTAURANT_MERCHANT_ID" ] && [ "$RESTAURANT_MERCHANT_ID" != "null" ]; then
            success "Restaurant merchant created with ID: $RESTAURANT_MERCHANT_ID"
        fi
    fi
    
    # Test international merchant creation
    response=$(test_endpoint "POST" "/api/v1/partners/$PARTNER_ID/merchants" \
        "$international_data" 201 "Create International Merchant")
    
    if [ $? -eq 0 ]; then
        INTERNATIONAL_MERCHANT_ID=$(extract_json_value "$response" ".data.id")
        if [ -n "$INTERNATIONAL_MERCHANT_ID" ] && [ "$INTERNATIONAL_MERCHANT_ID" != "null" ]; then
            success "International merchant created with ID: $INTERNATIONAL_MERCHANT_ID"
        fi
    fi
    
    echo ""
}

test_merchant_listing() {
    log "=== TESTING MERCHANT LISTING ==="
    
    test_endpoint "GET" "/api/v1/partners/$PARTNER_ID/merchants" \
        "" 200 "List All Merchants"
    
    test_endpoint "GET" "/api/v1/partners/$PARTNER_ID/merchants?status=ACTIVE" \
        "" 200 "List Active Merchants"
    
    test_endpoint "GET" "/api/v1/partners/$PARTNER_ID/merchants?business_type=RETAIL" \
        "" 200 "List Retail Merchants"
    
    echo ""
}

test_merchant_details() {
    log "=== TESTING MERCHANT DETAILS ==="
    
    if [ -n "$RETAIL_MERCHANT_ID" ]; then
        test_endpoint "GET" "/api/v1/partners/$PARTNER_ID/merchants/$RETAIL_MERCHANT_ID" \
            "" 200 "Get Retail Merchant Details"
    else
        warn "Skipping merchant details test - no retail merchant ID available"
    fi
    
    echo ""
}

test_merchant_updates() {
    log "=== TESTING MERCHANT UPDATES ==="
    
    if [ -n "$RETAIL_MERCHANT_ID" ]; then
        local update_data='{
            "brand_name": "Updated Test Store Name",
            "contact_email": "updated@teststore.com"
        }'
        
        test_endpoint "PUT" "/api/v1/partners/$PARTNER_ID/merchants/$RETAIL_MERCHANT_ID" \
            "$update_data" 200 "Update Merchant Information"
    else
        warn "Skipping merchant update test - no retail merchant ID available"
    fi
    
    echo ""
}

test_merchant_status() {
    log "=== TESTING MERCHANT STATUS MANAGEMENT ==="
    
    if [ -n "$RESTAURANT_MERCHANT_ID" ]; then
        # Test status transitions
        statuses=("SUSPENDED" "ACTIVE" "INACTIVE" "ACTIVE")
        
        for status in "${statuses[@]}"; do
            local status_data='{"status": "'$status'"}'
            test_endpoint "PATCH" "/api/v1/partners/$PARTNER_ID/merchants/$RESTAURANT_MERCHANT_ID/status" \
                "$status_data" 200 "Update Status to $status"
            sleep 1  # Brief pause between status changes
        done
    else
        warn "Skipping status test - no restaurant merchant ID available"
    fi
    
    echo ""
}

test_merchant_validation() {
    log "=== TESTING MERCHANT VALIDATION ==="
    
    if [ -n "$RETAIL_MERCHANT_ID" ]; then
        test_endpoint "GET" "/api/v1/partners/$PARTNER_ID/merchants/$RETAIL_MERCHANT_ID/validate" \
            "" 200 "Validate Merchant"
    else
        warn "Skipping validation test - no merchant ID available"
    fi
    
    echo ""
}

test_transaction_limits() {
    log "=== TESTING TRANSACTION LIMITS ==="
    
    if [ -n "$INTERNATIONAL_MERCHANT_ID" ]; then
        amounts=("100.00" "1000.00" "5000.00" "25000.00")
        
        for amount in "${amounts[@]}"; do
            local limit_data='{"amount": "'$amount'"}'
            test_endpoint "POST" "/api/v1/partners/$PARTNER_ID/merchants/$INTERNATIONAL_MERCHANT_ID/check-limits" \
                "$limit_data" 200 "Check Limits for ₹$amount"
        done
    else
        warn "Skipping limits test - no international merchant ID available"
    fi
    
    echo ""
}

test_merchant_search() {
    log "=== TESTING MERCHANT SEARCH ==="
    
    test_endpoint "GET" "/api/v1/partners/$PARTNER_ID/merchants-search?q=Test" \
        "" 200 "Search Merchants by Name"
    
    test_endpoint "GET" "/api/v1/partners/$PARTNER_ID/merchants-search?status=ACTIVE" \
        "" 200 "Search Active Merchants"
    
    test_endpoint "GET" "/api/v1/partners/$PARTNER_ID/merchants-search?q=Test&status=ACTIVE" \
        "" 200 "Search with Multiple Filters"
    
    echo ""
}

test_merchant_statistics() {
    log "=== TESTING MERCHANT STATISTICS ==="
    
    test_endpoint "GET" "/api/v1/partners/$PARTNER_ID/merchants-stats" \
        "" 200 "Get Merchant Statistics"
    
    echo ""
}

test_qr_generation() {
    log "=== TESTING QR CODE GENERATION ==="
    
    if [ -n "$RETAIL_MERCHANT_ID" ]; then
        local qr_data='{
            "merchant_id": "'$RETAIL_MERCHANT_ID'",
            "amount": "500.00",
            "currency": "INR",
            "note": "Test payment",
            "expiry_minutes": 15
        }'
        
        response=$(test_endpoint "POST" "/api/v1/qr-generate" \
            "$qr_data" 201 "Generate QR Code")
        
        if [ $? -eq 0 ]; then
            QR_ID=$(extract_json_value "$response" ".qr_id")
            if [ -n "$QR_ID" ] && [ "$QR_ID" != "null" ]; then
                success "QR code generated with ID: $QR_ID"
                
                # Test QR status
                test_endpoint "GET" "/api/v1/qr-status/$QR_ID" \
                    "" 200 "Check QR Status"
            fi
        fi
    else
        warn "Skipping QR generation test - no merchant ID available"
    fi
    
    echo ""
}

test_error_scenarios() {
    log "=== TESTING ERROR SCENARIOS ==="
    
    # Test duplicate merchant code
    local duplicate_data=$(get_merchant_template "retail")
    test_endpoint "POST" "/api/v1/partners/$PARTNER_ID/merchants" \
        "$duplicate_data" 409 "Duplicate Merchant Code (Expected Error)"
    
    # Test invalid VPA format
    local invalid_vpa_data='{
        "merchant_code": "INVALID'$(date +%s)'",
        "brand_name": "Invalid VPA Test",
        "merchant_vpa": "invalid-vpa-format",
        "business_type": "RETAIL"
    }'
    
    test_endpoint "POST" "/api/v1/partners/$PARTNER_ID/merchants" \
        "$invalid_vpa_data" 422 "Invalid VPA Format (Expected Error)"
    
    # Test missing required fields
    local incomplete_data='{"merchant_code": "INCOMPLETE'$(date +%s)'"}'
    test_endpoint "POST" "/api/v1/partners/$PARTNER_ID/merchants" \
        "$incomplete_data" 422 "Missing Required Fields (Expected Error)"
    
    # Test non-existent merchant
    test_endpoint "GET" "/api/v1/partners/$PARTNER_ID/merchants/NON_EXISTENT_ID" \
        "" 404 "Non-existent Merchant (Expected Error)"
    
    # Test invalid partner
    test_endpoint "GET" "/api/v1/partners/INVALID_PARTNER/merchants" \
        "" 403 "Invalid Partner Access (Expected Error)"
    
    echo ""
}

# Print usage
print_usage() {
    echo "Merchant API Testing Script"
    echo ""
    echo "Usage: $0 [options]"
    echo ""
    echo "Options:"
    echo "  --help                Show this help message"
    echo "  --quick              Run only basic tests"
    echo "  --full               Run comprehensive test suite"
    echo "  --errors-only        Run only error scenario tests"
    echo ""
    echo "Environment Variables:"
    echo "  API_TOKEN            Partner API authentication token (required)"
    echo "  BASE_URL             Base API URL (default: https://api.mercurypay.com)"
    echo "  PARTNER_ID           Partner ID for testing (default: PARTNER_001)"
    echo ""
    echo "Examples:"
    echo "  export API_TOKEN='your_token_here'"
    echo "  export PARTNER_ID='PARTNER_001'"
    echo "  $0 --full"
    echo ""
}

# Main execution
main() {
    local test_type="full"
    
    # Parse command line arguments
    while [[ $# -gt 0 ]]; do
        case $1 in
            --help)
                print_usage
                exit 0
                ;;
            --quick)
                test_type="quick"
                shift
                ;;
            --full)
                test_type="full"
                shift
                ;;
            --errors-only)
                test_type="errors"
                shift
                ;;
            *)
                error "Unknown option: $1"
                print_usage
                exit 1
                ;;
        esac
    done
    
    # Check prerequisites
    if [ -z "$API_TOKEN" ] || [ "$API_TOKEN" = "your_token_here" ]; then
        error "API_TOKEN environment variable is required"
        echo "Please set it with: export API_TOKEN='your_actual_token'"
        exit 1
    fi
    
    if ! command -v curl >/dev/null 2>&1; then
        error "curl is required but not installed"
        exit 1
    fi
    
    # Display configuration
    log "Starting Merchant API Tests"
    log "Base URL: $BASE_URL"
    log "Partner ID: $PARTNER_ID"
    log "Test Type: $test_type"
    echo ""
    
    # Initialize variables for storing created resource IDs
    RETAIL_MERCHANT_ID=""
    RESTAURANT_MERCHANT_ID=""
    INTERNATIONAL_MERCHANT_ID=""
    QR_ID=""
    
    # Run tests based on type
    case $test_type in
        "quick")
            log "Running Quick Test Suite..."
            test_merchant_creation
            test_merchant_listing
            test_merchant_statistics
            ;;
        "errors")
            log "Running Error Scenario Tests..."
            test_error_scenarios
            ;;
        "full"|*)
            log "Running Comprehensive Test Suite..."
            test_merchant_creation
            test_merchant_listing
            test_merchant_details
            test_merchant_updates
            test_merchant_status
            test_merchant_validation
            test_transaction_limits
            test_merchant_search
            test_merchant_statistics
            test_qr_generation
            test_error_scenarios
            ;;
    esac
    
    # Summary
    success "Test suite completed!"
    
    if [ -n "$RETAIL_MERCHANT_ID" ] || [ -n "$RESTAURANT_MERCHANT_ID" ] || [ -n "$INTERNATIONAL_MERCHANT_ID" ]; then
        log "Created merchants for testing:"
        [ -n "$RETAIL_MERCHANT_ID" ] && log "  • Retail: $RETAIL_MERCHANT_ID"
        [ -n "$RESTAURANT_MERCHANT_ID" ] && log "  • Restaurant: $RESTAURANT_MERCHANT_ID"
        [ -n "$INTERNATIONAL_MERCHANT_ID" ] && log "  • International: $INTERNATIONAL_MERCHANT_ID"
    fi
    
    [ -n "$QR_ID" ] && log "Created QR code: $QR_ID"
    
    echo ""
    log "For detailed testing with Python script, run:"
    log "  python3 merchant_api_tester.py --verbose"
}

# Run main function
main "$@"
