#!/bin/bash

echo "🔬 Date Timezone Bug Verification Test"
echo "====================================="
echo ""
echo "Server: http://localhost:9000"
echo "Supabase: http://127.0.0.1:54321"
echo ""

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

# Test counter
PASSED=0
FAILED=0

# Function to test a date
test_date() {
    local TEST_NAME="$1"
    local INPUT_DATE="$2"

    echo "📅 Testing: $TEST_NAME"
    echo "   Input date: $INPUT_DATE"

    # Get CSRF token
    CSRF_RESPONSE=$(curl -s -c /tmp/cookies.txt http://localhost:9000/api/csrf)
    CSRF_TOKEN=$(echo $CSRF_RESPONSE | jq -r '.csrfToken')

    if [ -z "$CSRF_TOKEN" ] || [ "$CSRF_TOKEN" = "null" ]; then
        echo -e "   ${RED}❌ Failed to get CSRF token${NC}"
        FAILED=$((FAILED + 1))
        return 1
    fi

    # Create unique email
    TIMESTAMP=$(date +%s)
    EMAIL="datetest+${TIMESTAMP}@test.com"

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

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

    if [ -z "$BOOKING_ID" ] || [ "$BOOKING_ID" = "null" ]; then
        echo -e "   ${RED}❌ Failed to create booking${NC}"
        echo "   Response: $BOOKING_RESPONSE"
        FAILED=$((FAILED + 1))
        return 1
    fi

    echo "   ✅ Booking created: ID $BOOKING_ID"

    # Wait for DB write
    sleep 2

    # Query database using Supabase API
    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")

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

    echo "   Expected: $INPUT_DATE"
    echo "   Actual:   $DB_DATE"

    # Compare dates
    if [ "$DB_DATE" = "$INPUT_DATE" ]; then
        echo -e "   ${GREEN}✅ PASS${NC}"
        PASSED=$((PASSED + 1))
    else
        echo -e "   ${RED}❌ FAIL${NC}"
        FAILED=$((FAILED + 1))
    fi

    echo ""
}

# Run test cases
test_date "Original Bug Date (Oct 27)" "2025-10-27"
test_date "Earlier Date (Oct 23)" "2025-10-23"
test_date "Later Date (Nov 1)" "2025-11-01"
test_date "Month Boundary (Oct 31)" "2025-10-31"
test_date "Start of Month (Nov 1)" "2025-11-01"

# Summary
echo ""
echo "📊 TEST SUMMARY"
echo "====================================="
echo "Total Tests: $((PASSED + FAILED))"
echo -e "${GREEN}✅ Passed: $PASSED${NC}"
echo -e "${RED}❌ Failed: $FAILED${NC}"
echo ""

# Final verdict
echo "🎯 FINAL VERDICT"
echo "====================================="
if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}✅ BUG IS FIXED!${NC}"
    echo "All dates saved correctly without timezone shifting."
    exit 0
else
    echo -e "${RED}❌ BUG STILL EXISTS!${NC}"
    echo "$FAILED test(s) failed - dates are being shifted."
    exit 1
fi
