#!/bin/bash

# Security Testing Script for SellZaki
# Tests rate limiting, input validation, and auto-blocking

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

# Configuration
BASE_URL="https://tyson.sellzaki.com"
TOKEN="${SELLZAKI_TOKEN:-YOUR_TOKEN_HERE}"

echo "🛡️  SellZaki Security Testing"
echo "================================"
echo ""

# Check if token is set
if [ "$TOKEN" = "YOUR_TOKEN_HERE" ]; then
    echo -e "${RED}❌ Error: Please set SELLZAKI_TOKEN environment variable${NC}"
    echo "   export SELLZAKI_TOKEN='your-actual-token'"
    exit 1
fi

# Test 1: Minimum Length Validation
echo "Test 1: Minimum Length Validation"
echo "-----------------------------------"
echo "Testing single character search (should fail)..."
RESPONSE=$(curl -s -w "\n%{http_code}" -H "Authorization: Bearer $TOKEN" \
    "$BASE_URL/api/products/search?q=t")
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
BODY=$(echo "$RESPONSE" | head -n-1)

if [ "$HTTP_CODE" = "200" ] && echo "$BODY" | grep -q "at least 2 characters"; then
    echo -e "${GREEN}✅ PASS: Single-char search rejected${NC}"
elif [ "$HTTP_CODE" != "200" ]; then
    echo -e "${GREEN}✅ PASS: Single-char search rejected (HTTP $HTTP_CODE)${NC}"
else
    echo -e "${RED}❌ FAIL: Single-char search should be rejected${NC}"
    echo "Response: $BODY"
fi
echo ""

# Test 2: Valid Search
echo "Test 2: Valid Search (2+ characters)"
echo "-------------------------------------"
echo "Testing valid search (should work)..."
RESPONSE=$(curl -s -w "\n%{http_code}" -H "Authorization: Bearer $TOKEN" \
    "$BASE_URL/api/products/search?q=test")
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)

if [ "$HTTP_CODE" = "200" ]; then
    echo -e "${GREEN}✅ PASS: Valid search works${NC}"
else
    echo -e "${RED}❌ FAIL: Valid search should work (got HTTP $HTTP_CODE)${NC}"
fi
echo ""

# Test 3: Rate Limiting
echo "Test 3: Rate Limiting (10 requests/minute)"
echo "-------------------------------------------"
echo "Sending 12 requests rapidly..."
SUCCESS_COUNT=0
BLOCKED_COUNT=0

for i in {1..12}; do
    HTTP_CODE=$(curl -s -w "%{http_code}" -o /dev/null -H "Authorization: Bearer $TOKEN" \
        "$BASE_URL/api/products/search?q=test")
    
    if [ "$HTTP_CODE" = "200" ]; then
        SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
        echo -n "."
    elif [ "$HTTP_CODE" = "429" ]; then
        BLOCKED_COUNT=$((BLOCKED_COUNT + 1))
        echo -n "X"
    else
        echo -n "?"
    fi
    
    sleep 0.5
done

echo ""
echo "Results: $SUCCESS_COUNT successful, $BLOCKED_COUNT blocked"

if [ $SUCCESS_COUNT -le 10 ] && [ $BLOCKED_COUNT -ge 2 ]; then
    echo -e "${GREEN}✅ PASS: Rate limiting working (blocked after 10 requests)${NC}"
elif [ $BLOCKED_COUNT -eq 0 ]; then
    echo -e "${YELLOW}⚠️  WARNING: No requests blocked - rate limiting may not be active${NC}"
else
    echo -e "${YELLOW}⚠️  PARTIAL: Rate limiting active but threshold may be different${NC}"
fi
echo ""

# Test 4: Pattern Detection (requires multiple single-char attempts)
echo "Test 4: Pattern Detection & Auto-Blocking"
echo "------------------------------------------"
echo "Sending 5 single-character searches (should trigger auto-block)..."
PATTERN_BLOCKED=false

for i in {1..5}; do
    HTTP_CODE=$(curl -s -w "%{http_code}" -o /dev/null -H "Authorization: Bearer $TOKEN" \
        "$BASE_URL/api/products/search?q=a")
    
    if [ "$HTTP_CODE" = "429" ]; then
        PATTERN_BLOCKED=true
        echo -e "${GREEN}✅ Request $i: Blocked (429)${NC}"
    else
        echo "Request $i: HTTP $HTTP_CODE"
    fi
    
    sleep 1
done

if [ "$PATTERN_BLOCKED" = true ]; then
    echo -e "${GREEN}✅ PASS: Pattern detection working${NC}"
else
    echo -e "${YELLOW}⚠️  WARNING: Pattern detection may not be active or threshold not reached${NC}"
fi
echo ""

# Test 5: Check if blocked IP can still access
echo "Test 5: Verify Site Accessibility"
echo "----------------------------------"
HTTP_CODE=$(curl -s -w "%{http_code}" -o /dev/null "$BASE_URL")

if [ "$HTTP_CODE" = "200" ]; then
    echo -e "${GREEN}✅ PASS: Site is accessible${NC}"
else
    echo -e "${RED}❌ FAIL: Site returned HTTP $HTTP_CODE${NC}"
fi
echo ""

# Summary
echo "================================"
echo "📊 Test Summary"
echo "================================"
echo ""
echo "✅ = Test passed"
echo "⚠️  = Warning (may need attention)"
echo "❌ = Test failed"
echo ""
echo "If all tests passed, your security implementation is working correctly!"
echo ""
echo "To monitor in real-time:"
echo "  sudo tail -f /var/log/nginx/access.log"
echo "  tail -f storage/logs/laravel.log | grep -i suspicious"
echo ""
echo "To block an IP manually:"
echo "  php artisan security:block-ip <IP> --minutes=1440"
echo ""
