#!/bin/bash

# Script to verify all security fixes are properly implemented
# Run from mawidi-site directory: bash ../scripts/verify-security-fixes.sh

echo "🔍 Verifying Security & Bug Fixes..."
echo "======================================"
echo ""

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

ERRORS=0

# Function to check if a pattern exists in a file
check_pattern() {
  local file=$1
  local pattern=$2
  local description=$3

  if grep -q "$pattern" "$file" 2>/dev/null; then
    echo -e "${GREEN}✓${NC} $description"
  else
    echo -e "${RED}✗${NC} $description"
    ERRORS=$((ERRORS + 1))
  fi
}

# Function to check if a pattern does NOT exist in a file
check_pattern_absent() {
  local file=$1
  local pattern=$2
  local description=$3

  if ! grep -q "$pattern" "$file" 2>/dev/null; then
    echo -e "${GREEN}✓${NC} $description"
  else
    echo -e "${RED}✗${NC} $description (pattern should not exist)"
    ERRORS=$((ERRORS + 1))
  fi
}

echo "1. Currency Conversion Implementation"
check_pattern "app/api/signup/checkout/route.ts" "CURRENCY_CONVERSION_RATES" "Currency conversion rates defined"
check_pattern "app/api/signup/checkout/route.ts" "function convertSetupFee" "Setup fee conversion function exists"
check_pattern "app/api/signup/checkout/route.ts" "setupFeeAmount = convertSetupFee" "Setup fee conversion applied"
echo ""

echo "2. Price Tampering Prevention"
check_pattern "app/api/signup/checkout/route.ts" "const expectedPriceId = await getStripePriceId" "Server-side price validation implemented"
check_pattern "app/api/signup/checkout/route.ts" "if (stripePriceId !== expectedPriceId)" "Price comparison check exists"
check_pattern "app/api/signup/checkout/route.ts" "Price tampering detected" "Security logging present"
echo ""

echo "3. Conditional Setup Fee Metadata"
check_pattern "app/api/signup/checkout/route.ts" "includeSetupFee &&" "Conditional metadata spreading"
check_pattern "app/api/signup/checkout/route.ts" "setup_fee_currency" "Currency included in metadata"
echo ""

echo "4. Idempotent Stripe Object Creation"
check_pattern "app/api/signup/checkout/route.ts" "IDEMPOTENT" "Idempotency comments present"
check_pattern "app/api/signup/checkout/route.ts" "stripe.products.search" "Product search for reuse"
check_pattern "app/api/signup/checkout/route.ts" "stripe.prices.search" "Price search for reuse"
check_pattern "app/api/signup/checkout/route.ts" "Reusing existing setup fee product" "Product reuse logging"
check_pattern "app/api/signup/checkout/route.ts" "Reusing existing setup fee price" "Price reuse logging"
echo ""

echo "5. Currency Validation (Checkout Route)"
check_pattern "app/api/signup/checkout/route.ts" "ALLOWED_CURRENCIES = \['QAR', 'AED', 'SAR', 'USD'\]" "Allowed currencies whitelist"
check_pattern "app/api/signup/checkout/route.ts" "ALLOWED_CURRENCIES.includes" "Currency whitelist validation"
echo ""

echo "6. Currency Validation (Stripe Price Route)"
check_pattern "app/api/stripe-price/route.ts" "ALLOWED_CURRENCIES = \['QAR', 'AED', 'SAR', 'USD'\]" "Allowed currencies whitelist"
check_pattern "app/api/stripe-price/route.ts" "currencyParam.toUpperCase()" "Currency normalization"
check_pattern "app/api/stripe-price/route.ts" "Invalid currency requested" "Currency validation logging"
echo ""

echo "7. Missing Context Error Display"
check_pattern "app/[lang]/signup/onboarding/page.tsx" "if (validationError)" "Validation error check"
check_pattern "app/[lang]/signup/onboarding/page.tsx" "Validation Error" "Error display component"
echo ""

echo "8. Retry Event Handling"
check_pattern "app/[lang]/signup/onboarding/page.tsx" "const performCheckout = async" "Extracted async checkout function"
check_pattern "app/[lang]/signup/onboarding/page.tsx" "onRetry={performCheckout}" "Retry using async function"
check_pattern_absent "app/[lang]/signup/onboarding/page.tsx" "handleSubmit(new Event" "No synthetic event creation"
echo ""

echo "9. Duplicate Logging Removed"
# Count occurrences of 'Creating checkout session'
OCCURRENCES=$(grep -c "Creating checkout session" "app/[lang]/signup/onboarding/page.tsx" 2>/dev/null || echo "0")
if [ "$OCCURRENCES" -eq "1" ]; then
  echo -e "${GREEN}✓${NC} Only one 'Creating checkout session' log statement"
else
  echo -e "${RED}✗${NC} Expected 1 'Creating checkout session' log, found $OCCURRENCES"
  ERRORS=$((ERRORS + 1))
fi
echo ""

echo "10. Arabic Recovery Steps Fallback"
check_pattern "app/[lang]/signup/components/CheckoutErrorDisplay.tsx" "recoveryStepsAr.length > 0" "Arabic fallback logic"
echo ""

echo "======================================"
if [ $ERRORS -eq 0 ]; then
  echo -e "${GREEN}✅ All security fixes verified successfully!${NC}"
  echo ""
  echo "Summary:"
  echo "  ✓ Currency conversion implemented"
  echo "  ✓ Price tampering prevention active"
  echo "  ✓ Setup fee metadata conditional"
  echo "  ✓ Idempotent Stripe operations"
  echo "  ✓ Currency validation enforced"
  echo "  ✓ UX improvements applied"
  echo "  ✓ Code quality enhanced"
  exit 0
else
  echo -e "${RED}❌ Found $ERRORS issues${NC}"
  echo ""
  echo "Please review the failed checks above and ensure all fixes are properly applied."
  exit 1
fi
