#!/bin/bash
#
# End-to-End API Test for Date Bug
# Tests the full flow: API → Database verification
#

echo "🔬 End-to-End API Date Bug Test"
echo "================================"
echo ""

# Get a CSRF token and extract from cookie
RESPONSE=$(curl -s -c /tmp/test_cookies.txt -D /tmp/test_headers.txt http://localhost:9000/api/csrf)
echo "✅ CSRF endpoint response: $RESPONSE"

# Extract CSRF token from cookie file
CSRF_TOKEN=$(grep csrf-token /tmp/test_cookies.txt | awk '{print $7}')
echo "✅ CSRF token: $CSRF_TOKEN"
echo ""

# Test date: October 27, 2025 (the original bug date)
TEST_DATE="2025-10-27"
TEST_EMAIL="e2e-test-$(date +%s)@test.com"

echo "📅 Creating booking for: $TEST_DATE"
echo "📧 Email: $TEST_EMAIL"
echo ""

# Create booking
BOOKING_RESPONSE=$(curl -s -b /tmp/test_cookies.txt \
  -X POST http://localhost:9000/api/demo/book \
  -H "Content-Type: application/json" \
  -H "X-CSRF-Token: $CSRF_TOKEN" \
  -d "{
    \"appointmentDate\": \"${TEST_DATE}T00:00:00.000Z\",
    \"appointmentTime\": \"14:30\",
    \"fullName\": \"Ahmad Testing\",
    \"email\": \"$TEST_EMAIL\",
    \"telephone\": \"+966501234567\",
    \"duration\": \"1hr\",
    \"language\": \"en\"
  }")

echo "API Response:"
echo "$BOOKING_RESPONSE" | jq
echo ""

# Extract booking ID
BOOKING_ID=$(echo "$BOOKING_RESPONSE" | jq -r '.bookingId')

if [ "$BOOKING_ID" = "null" ] || [ -z "$BOOKING_ID" ]; then
  echo "❌ FAILED: Could not create booking"
  echo "Response: $BOOKING_RESPONSE"
  exit 1
fi

echo "✅ Booking created successfully"
echo "   Booking ID: $BOOKING_ID"
echo ""

# Wait for database write
sleep 2

# Query database
echo "🔍 Querying database for booking..."
DB_RESPONSE=$(curl -s \
  -H "apikey: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU" \
  "http://127.0.0.1:54321/rest/v1/demo_bookings?id=eq.$BOOKING_ID&select=id,appointment_date,appointment_time,email")

echo "Database Response:"
echo "$DB_RESPONSE" | jq
echo ""

# Extract date from response
DB_DATE=$(echo "$DB_RESPONSE" | jq -r '.[0].appointment_date' | cut -d'T' -f1)

echo "================================"
echo "📊 VERIFICATION RESULTS"
echo "================================"
echo ""
echo "User selected date:    $TEST_DATE"
echo "Database stored date:  $DB_DATE"
echo ""

# Compare dates
if [ "$DB_DATE" = "$TEST_DATE" ]; then
  echo "✅ SUCCESS: Date matches exactly!"
  echo ""
  echo "🎯 FINAL VERDICT: BUG IS FIXED ✅"
  echo "User selected Oct 27 → Database has Oct 27"
  echo "No timezone shifting occurred."
  exit 0
else
  echo "❌ FAILURE: Date mismatch!"
  echo ""
  echo "🎯 FINAL VERDICT: BUG STILL EXISTS ❌"
  echo "Expected: $TEST_DATE"
  echo "Got: $DB_DATE"
  exit 1
fi
