/**
 * Date Timezone Bug Verification Test
 *
 * Tests that user-selected dates are saved correctly without timezone shifting
 * Bug: User selects Oct 27 → Database saved Oct 26
 * Fix: Backend extracts date-only string before saving
 */

import { createClient } from '@supabase/supabase-js';

const SERVER_URL = 'http://localhost:9000';
const SUPABASE_URL = 'http://127.0.0.1:54321';
const SUPABASE_SERVICE_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU';

const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY);

interface TestResult {
  testName: string;
  selectedDate: string;
  expectedDate: string;
  actualDate: string;
  passed: boolean;
  bookingId?: string;
  error?: string;
}

async function getCSRFToken(): Promise<{ token: string; cookies: string[] }> {
  const response = await fetch(`${SERVER_URL}/api/csrf`, {
    method: 'GET',
  });

  if (!response.ok) {
    throw new Error('Failed to get CSRF token');
  }

  const data = await response.json();
  const cookies = response.headers.get('set-cookie')?.split(',') || [];

  return { token: data.csrfToken, cookies };
}

async function createBooking(date: string, csrfToken: string, cookies: string[]): Promise<any> {
  const bookingData = {
    appointmentDate: `${date}T00:00:00.000Z`,
    appointmentTime: '14:30',
    fullName: 'Date Test User',
    email: `datetest+${Date.now()}@test.com`,
    telephone: '+966501234567',
    duration: '1hr',
    language: 'en',
  };

  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    'x-csrf-token': csrfToken,
  };

  // Add cookies if available
  if (cookies.length > 0) {
    headers['Cookie'] = cookies.join('; ');
  }

  const response = await fetch(`${SERVER_URL}/api/demo/book`, {
    method: 'POST',
    headers,
    body: JSON.stringify(bookingData),
  });

  if (!response.ok) {
    const error = await response.text();
    throw new Error(`Booking failed: ${error}`);
  }

  return response.json();
}

async function getBookingFromDB(bookingId: string): Promise<any> {
  const { data, error } = await supabase
    .from('demo_bookings')
    .select('id, appointment_date, appointment_time')
    .eq('id', bookingId)
    .single();

  if (error) {
    throw new Error(`Database query failed: ${error.message}`);
  }

  return data;
}

async function testDate(testName: string, inputDate: string): Promise<TestResult> {
  console.log(`\n📅 Testing: ${testName}`);
  console.log(`   Input date: ${inputDate}`);

  try {
    // Get CSRF token and cookies
    const { token, cookies } = await getCSRFToken();

    // Create booking
    const bookingResponse = await createBooking(inputDate, token, cookies);
    const bookingId = bookingResponse.bookingId;

    console.log(`   ✅ Booking created: ID ${bookingId}`);

    // Wait for DB write
    await new Promise(resolve => setTimeout(resolve, 1000));

    // Query database
    const dbBooking = await getBookingFromDB(bookingId);

    // Extract date part from database value
    const actualDate = dbBooking.appointment_date.split('T')[0];
    const expectedDate = inputDate;

    const passed = actualDate === expectedDate;

    console.log(`   Expected: ${expectedDate}`);
    console.log(`   Actual:   ${actualDate}`);
    console.log(`   ${passed ? '✅ PASS' : '❌ FAIL'}`);

    return {
      testName,
      selectedDate: inputDate,
      expectedDate,
      actualDate,
      passed,
      bookingId,
    };
  } catch (error) {
    console.log(`   ❌ ERROR: ${error}`);
    return {
      testName,
      selectedDate: inputDate,
      expectedDate: inputDate,
      actualDate: 'N/A',
      passed: false,
      error: String(error),
    };
  }
}

async function runTests() {
  console.log('🔬 Date Timezone Bug Verification Test');
  console.log('=====================================\n');
  console.log('Server: ' + SERVER_URL);
  console.log('Supabase: ' + SUPABASE_URL);

  const testCases = [
    { name: 'Original Bug Date (Oct 27)', date: '2025-10-27' },
    { name: 'Earlier Date (Oct 23)', date: '2025-10-23' },
    { name: 'Later Date (Nov 1)', date: '2025-11-01' },
    { name: 'Month Boundary (Oct 31)', date: '2025-10-31' },
    { name: 'Start of Month (Nov 1)', date: '2025-11-01' },
  ];

  const results: TestResult[] = [];

  for (const testCase of testCases) {
    const result = await testDate(testCase.name, testCase.date);
    results.push(result);

    // Rate limiting: wait between requests
    await new Promise(resolve => setTimeout(resolve, 2000));
  }

  // Summary
  console.log('\n\n📊 TEST SUMMARY');
  console.log('=====================================');

  const passed = results.filter(r => r.passed).length;
  const failed = results.filter(r => !r.passed).length;

  console.log(`Total Tests: ${results.length}`);
  console.log(`✅ Passed: ${passed}`);
  console.log(`❌ Failed: ${failed}`);
  console.log('');

  // Detailed results
  console.log('📋 DETAILED RESULTS');
  console.log('=====================================');
  results.forEach(result => {
    const status = result.passed ? '✅' : '❌';
    console.log(`${status} ${result.testName}`);
    console.log(`   Selected: ${result.selectedDate}`);
    console.log(`   Expected: ${result.expectedDate}`);
    console.log(`   Actual:   ${result.actualDate}`);
    if (result.bookingId) {
      console.log(`   Booking ID: ${result.bookingId}`);
    }
    if (result.error) {
      console.log(`   Error: ${result.error}`);
    }
    console.log('');
  });

  // Final verdict
  console.log('🎯 FINAL VERDICT');
  console.log('=====================================');
  if (failed === 0) {
    console.log('✅ BUG IS FIXED!');
    console.log('All dates saved correctly without timezone shifting.');
  } else {
    console.log('❌ BUG STILL EXISTS!');
    console.log(`${failed} test(s) failed - dates are being shifted.`);
  }

  // Database verification query
  console.log('\n📝 DATABASE VERIFICATION QUERY');
  console.log('=====================================');
  const bookingIds = results.filter(r => r.bookingId).map(r => r.bookingId);
  if (bookingIds.length > 0) {
    console.log('Run this query in Supabase Studio to verify:');
    console.log('');
    console.log('SELECT id, appointment_date, appointment_time, created_at');
    console.log('FROM demo_bookings');
    console.log(`WHERE id IN ('${bookingIds.join("','")}');`);
  }

  process.exit(failed > 0 ? 1 : 0);
}

// Run tests
runTests().catch(error => {
  console.error('❌ Test execution failed:', error);
  process.exit(1);
});
