#!/bin/bash

# Booking System Security Audit
# Tests seat reservation race conditions, payment flows, and booking logic

API="http://162.214.79.3"
HOST="dev.globalgalashow.com"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo "======================================"
echo "Booking System Security Audit"
echo "======================================"

PASS=0
FAIL=0
WARN=0

pass() { echo -e "${GREEN}✓ PASS${NC} - $1"; ((PASS++)); }
fail() { echo -e "${RED}✗ FAIL${NC} - $1"; ((FAIL++)); }
warn() { echo -e "${YELLOW}⚠ WARN${NC} - $1"; ((WARN++)); }
info() { echo -e "${BLUE}ℹ INFO${NC} - $1"; }

# ============================================================================
# SEAT RESERVATION SECURITY
# ============================================================================
echo -e "\n[SECTION 1] Seat Reservation Security"
echo "=========================================="

# Test: Hold token uniqueness
info "Testing hold token uniqueness..."
SESSION1="test-session-$(date +%s)-1"
SESSION2="test-session-$(date +%s)-2"

TOKEN1=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d "{\"event_id\":1,\"seat_ids\":[1],\"session_id\":\"$SESSION1\"}" \
    "$API/api/seats/hold" | grep -oP '"hold_token":"\K[^"]+' || echo "none")

TOKEN2=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d "{\"event_id\":1,\"seat_ids\":[1],\"session_id\":\"$SESSION2\"}" \
    "$API/api/seats/hold" | grep -oP '"hold_token":"\K[^"]+' || echo "none")

if [ "$TOKEN1" != "$TOKEN2" ] && [ "$TOKEN1" != "none" ]; then
    pass "Hold tokens are unique per session"
else
    warn "Hold token uniqueness should be verified"
fi

# Test: Seat double-booking prevention
info "Testing double-booking prevention..."
SEAT_ID=42
SESSION_A="double-test-a-$(date +%s)"
SESSION_B="double-test-b-$(date +%s)"

# First hold
HOLD1=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d "{\"event_id\":1,\"seat_ids\":[$SEAT_ID],\"session_id\":\"$SESSION_A\"}" \
    "$API/api/seats/hold")

# Second hold (should fail)
HOLD2=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d "{\"event_id\":1,\"seat_ids\":[$SEAT_ID],\"session_id\":\"$SESSION_B\"}" \
    "$API/api/seats/hold")

if echo "$HOLD2" | grep -qiE "conflict|already|unavailable|held"; then
    pass "Double-booking properly prevented"
else
    fail "CRITICAL: Double-booking may be possible!"
fi

# Test: Hold expiration
info "Testing hold expiration logic..."
RESPONSE=$(curl -s -H "Host: $HOST" "$API/api/seats/hold/expired-token-123")
if echo "$RESPONSE" | grep -qiE "expired|invalid|not found"; then
    pass "Expired hold tokens are rejected"
else
    warn "Hold expiration validation needs review"
fi

# Test: Hold token hijacking
info "Testing hold token authorization..."
# Try to confirm booking with someone else's token
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"session_id":"fake-session","hold_token":"stolen-token"}' \
    "$API/api/seats/confirm")
if echo "$RESPONSE" | grep -qiE "unauthorized|invalid|not found"; then
    pass "Hold token authorization enforced"
else
    warn "Hold token hijacking prevention should be verified"
fi

# Test: Seat ID manipulation
info "Testing seat ID validation..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"event_id":1,"seat_ids":[-1,0,999999],"session_id":"test"}' \
    "$API/api/seats/hold")
if echo "$RESPONSE" | grep -qiE "invalid|not found|error"; then
    pass "Invalid seat IDs are rejected"
else
    warn "Seat ID validation should be strengthened"
fi

# ============================================================================
# PRICING & PAYMENT INTEGRITY
# ============================================================================
echo -e "\n[SECTION 2] Pricing & Payment Integrity"
echo "=========================================="

# Test: Price tampering in hold request
info "Testing price tampering protection..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"event_id":1,"seat_ids":[1],"seat_pricing":{"1":0.01}}' \
    "$API/api/seats/hold")
# Server should validate pricing against database
if echo "$RESPONSE" | grep -qiE "success|held"; then
    warn "CRITICAL: Client-provided pricing accepted without server validation!"
else
    pass "Server-side price validation enforced"
fi

# Test: Currency manipulation
info "Testing currency consistency..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"amount":100,"currency":"BTC"}' \
    "$API/api/stripe/payment-intent")
if echo "$RESPONSE" | grep -qiE "currency|invalid|not supported"; then
    pass "Invalid currencies are rejected"
else
    warn "Currency validation needs review"
fi

# Test: Total amount recalculation
info "Testing server-side amount calculation..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"event_id":1,"seat_ids":[1,2,3],"total":1.00}' \
    "$API/api/payment/create-intent")
# Server should ignore client total and calculate its own
if echo "$RESPONSE" | grep -qE "amount"; then
    info "Payment amount recalculated server-side (verify manually)"
fi

# Test: Fee calculation tampering
info "Testing booking fee integrity..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"subtotal":100,"booking_fee":0,"tax":0}' \
    "$API/api/payment/create-intent")
if echo "$RESPONSE" | grep -qiE "calculated|fee"; then
    pass "Server recalculates fees"
else
    warn "Fee calculation should be server-side"
fi

# ============================================================================
# RACE CONDITIONS & CONCURRENCY
# ============================================================================
echo -e "\n[SECTION 3] Race Conditions & Concurrency"
echo "=========================================="

# Test: Concurrent booking attempts
info "Testing concurrent booking protection..."
SEAT_ID=100
SESSIONS=()
for i in {1..5}; do
    SESSIONS+=("race-test-$(date +%s%N)-$i")
done

# Launch concurrent hold requests
PIDS=()
for session in "${SESSIONS[@]}"; do
    (curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
        -d "{\"event_id\":1,\"seat_ids\":[$SEAT_ID],\"session_id\":\"$session\"}" \
        "$API/api/seats/hold" > "/tmp/booking-race-$session.json") &
    PIDS+=($!)
done

# Wait for all requests to complete
for pid in "${PIDS[@]}"; do
    wait $pid
done

# Count successes
SUCCESSES=0
for session in "${SESSIONS[@]}"; do
    if [ -f "/tmp/booking-race-$session.json" ]; then
        grep -q "success" "/tmp/booking-race-$session.json" && ((SUCCESSES++))
        rm -f "/tmp/booking-race-$session.json"
    fi
done

if [ $SUCCESSES -le 1 ]; then
    pass "Race condition protection working (only $SUCCESSES succeeded)"
else
    fail "CRITICAL: Race condition detected! $SUCCESSES concurrent bookings succeeded"
fi

# Test: Hold-Confirm race condition
info "Testing hold-confirm timing attack..."
SESSION="timing-attack-$(date +%s)"
# Hold seats
HOLD_RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d "{\"event_id\":1,\"seat_ids\":[50],\"session_id\":\"$SESSION\"}" \
    "$API/api/seats/hold")

TOKEN=$(echo "$HOLD_RESPONSE" | grep -oP '"hold_token":"\K[^"]+' || echo "none")

# Immediately try to confirm twice
CONFIRM1=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d "{\"session_id\":\"$SESSION\",\"hold_token\":\"$TOKEN\"}" \
    "$API/api/seats/confirm") &
PID1=$!

CONFIRM2=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d "{\"session_id\":\"$SESSION\",\"hold_token\":\"$TOKEN\"}" \
    "$API/api/seats/confirm") &
PID2=$!

wait $PID1 $PID2

warn "Hold-confirm race test completed (check for duplicate orders manually)"

# ============================================================================
# HOLD EXPIRATION & CLEANUP
# ============================================================================
echo -e "\n[SECTION 4] Hold Expiration & Cleanup"
echo "=========================================="

# Test: Expired hold handling
info "Testing expired hold behavior..."
OLD_SESSION="expired-$(date -d '20 minutes ago' +%s 2>/dev/null || date -v-20M +%s 2>/dev/null || echo '0')"
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d "{\"session_id\":\"$OLD_SESSION\",\"hold_token\":\"expired\"}" \
    "$API/api/seats/confirm")
if echo "$RESPONSE" | grep -qiE "expired|invalid|not found"; then
    pass "Expired holds cannot be confirmed"
else
    warn "Expired hold validation needs review"
fi

# Test: Hold release mechanism
info "Testing hold release..."
RELEASE_SESSION="release-test-$(date +%s)"
# Create hold
HOLD_RESP=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d "{\"event_id\":1,\"seat_ids\":[60],\"session_id\":\"$RELEASE_SESSION\"}" \
    "$API/api/seats/hold")

# Release hold
RELEASE_RESP=$(curl -s -X DELETE -H "Host: $HOST" -H "Content-Type: application/json" \
    -d "{\"session_id\":\"$RELEASE_SESSION\"}" \
    "$API/api/seats/hold")

if echo "$RELEASE_RESP" | grep -qiE "released|success"; then
    pass "Manual hold release works"
else
    warn "Hold release mechanism should be verified"
fi

# ============================================================================
# PAYMENT FLOW SECURITY
# ============================================================================
echo -e "\n[SECTION 5] Payment Flow Security"
echo "=========================================="

# Test: Payment without hold
info "Testing payment without seat hold..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"session_id":"no-hold-session"}' \
    "$API/api/payment/create-intent")
if echo "$RESPONSE" | grep -qiE "hold|reservation|not found|invalid"; then
    pass "Payment requires valid seat hold"
else
    warn "Payment flow should validate seat hold"
fi

# Test: Payment amount mismatch
info "Testing payment amount validation..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"hold_token":"test","amount":1,"expected_amount":100}' \
    "$API/api/stripe/confirm-payment")
if echo "$RESPONSE" | grep -qiE "mismatch|amount|invalid"; then
    pass "Payment amount validation enforced"
else
    warn "Payment amount mismatch detection needs review"
fi

# Test: Duplicate payment prevention (idempotency)
info "Testing payment idempotency..."
IDEMPOTENCY_KEY="test-$(date +%s)"
PAYMENT1=$(curl -s -X POST -H "Host: $HOST" -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
    -H "Content-Type: application/json" \
    -d '{"amount":100}' \
    "$API/api/stripe/payment-intent")

PAYMENT2=$(curl -s -X POST -H "Host: $HOST" -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
    -H "Content-Type: application/json" \
    -d '{"amount":100}' \
    "$API/api/stripe/payment-intent")

if [ "$PAYMENT1" = "$PAYMENT2" ]; then
    pass "Payment idempotency working"
else
    warn "Idempotency should prevent duplicate payments"
fi

# ============================================================================
# REFUND & CANCELLATION SECURITY
# ============================================================================
echo -e "\n[SECTION 6] Refund & Cancellation Security"
echo "=========================================="

# Test: Unauthorized refund
info "Testing refund authorization..."
RESPONSE=$(curl -s -X PUT -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"order_id":1,"amount":1000}' \
    "$API/api/admin/orders/1/refund")
if echo "$RESPONSE" | grep -qiE "401|403|unauthorized"; then
    pass "Refund requires admin authentication"
else
    fail "Refund endpoint accessible without auth!"
fi

# Test: Refund amount validation
info "Testing refund amount limits..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"order_id":1,"refund_amount":999999}' \
    "$API/api/admin/orders/1/refund")
if echo "$RESPONSE" | grep -qiE "amount|exceeds|invalid|unauthorized"; then
    pass "Refund amount validation in place"
else
    warn "Refund amount should not exceed order total"
fi

# Test: Duplicate refund prevention
info "Testing duplicate refund protection..."
warn "Duplicate refund prevention should be manually verified"

# ============================================================================
# SUMMARY
# ============================================================================
echo -e "\n======================================"
echo "Booking System Security Summary"
echo "======================================"
echo -e "${GREEN}Passed: $PASS${NC}"
echo -e "${YELLOW}Warnings: $WARN${NC}"
echo -e "${RED}Failed: $FAIL${NC}"
echo "======================================"

if [ $FAIL -gt 0 ]; then
    echo -e "${RED}⚠️  CRITICAL: $FAIL booking security issues found!${NC}"
    exit 1
else
    echo -e "${GREEN}✓ Booking system security audit passed${NC}"
    exit 0
fi
