/**
 * Test Date Fix - Verifies timezone bug is resolved
 *
 * Tests that dates are formatted correctly without UTC timezone shift
 */

import { config } from 'dotenv';
import path from 'path';

config({ path: path.resolve(__dirname, '../.env.local') });

// Colors
const colors = {
  reset: '\x1b[0m',
  green: '\x1b[32m',
  red: '\x1b[31m',
  yellow: '\x1b[33m',
  cyan: '\x1b[36m',
  bright: '\x1b[1m',
};

function log(message: string, color: keyof typeof colors = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

async function testDateFormatting() {
  log('\n🧪 Testing Date Formatting Fix\n', 'bright');

  // ========================================
  // Test 1: Date formatting function
  // ========================================
  log('Test 1: Date Formatting Logic', 'cyan');

  const formatDateOnly = (date: Date): string => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  // Test with different dates
  const testDates = [
    { date: new Date(2025, 10, 12), expected: '2025-11-12', label: 'Nov 12, 2025' },
    { date: new Date(2025, 11, 1), expected: '2025-12-01', label: 'Dec 1, 2025' },
    { date: new Date(2025, 11, 25), expected: '2025-12-25', label: 'Dec 25, 2025' },
  ];

  let allPassed = true;

  for (const test of testDates) {
    const formatted = formatDateOnly(test.date);
    const oldMethod = test.date.toISOString().split('T')[0];

    log(`\n   Testing: ${test.label}`, 'cyan');
    log(`   New method (formatDateOnly): ${formatted}`);
    log(`   Old method (toISOString): ${oldMethod}`);

    if (formatted === test.expected) {
      log(`   ✅ PASS: Formatted correctly as ${formatted}`, 'green');
    } else {
      log(`   ❌ FAIL: Expected ${test.expected}, got ${formatted}`, 'red');
      allPassed = false;
    }

    // Show the timezone issue with old method
    if (oldMethod !== test.expected) {
      log(`   ⚠️  Old method would have saved wrong date: ${oldMethod}`, 'yellow');
    }
  }

  // ========================================
  // Test 2: API Request Simulation
  // ========================================
  log('\n\nTest 2: API Submission Simulation', 'cyan');

  const selectedDate = new Date(2025, 10, 12); // Nov 12, 2025
  const formattedDate = formatDateOnly(selectedDate);

  log(`\n   User selects: ${selectedDate.toDateString()}`);
  log(`   Frontend sends: ${formattedDate}`);
  log(`   Backend receives: ${formattedDate}`);
  log(`   Backend splits 'T': ${formattedDate.split('T')[0]}`);
  log(`   Database stores: ${formattedDate}`);

  if (formattedDate === '2025-11-12') {
    log('\n   ✅ PASS: Date preserved correctly through entire flow!', 'green');
  } else {
    log('\n   ❌ FAIL: Date was corrupted', 'red');
    allPassed = false;
  }

  // ========================================
  // Test 3: Comparison with Old Buggy Method
  // ========================================
  log('\n\nTest 3: Comparing Old vs New Method', 'cyan');

  const testDate = new Date(2025, 10, 12, 0, 0, 0); // Nov 12, 2025 midnight local

  const oldMethod = testDate.toISOString(); // Buggy: converts to UTC
  const newMethod = formatDateOnly(testDate); // Fixed: local timezone

  log(`\n   Selected: Nov 12, 2025 (midnight local time)`);
  log(`   OLD (buggy): ${oldMethod}`);
  log(`   ├─ Full ISO: ${oldMethod}`);
  log(`   └─ After split: ${oldMethod.split('T')[0]}`);
  log(`   NEW (fixed): ${newMethod}`);
  log(`   ├─ No timezone conversion`);
  log(`   └─ Pure date: ${newMethod}`);

  const oldDateOnly = oldMethod.split('T')[0];

  if (oldDateOnly !== newMethod) {
    log(`\n   ✅ Confirmed: Old method had timezone bug (${oldDateOnly} !== ${newMethod})`, 'green');
    log(`   ✅ New method fixes the issue!`, 'green');
  }

  // ========================================
  // Final Summary
  // ========================================
  log('\n' + '='.repeat(60), 'bright');
  if (allPassed) {
    log('✅ ALL TESTS PASSED - Date Fix is Working!', 'green');
  } else {
    log('❌ SOME TESTS FAILED - Review output above', 'red');
  }
  log('='.repeat(60) + '\n', 'bright');

  // ========================================
  // Next Steps
  // ========================================
  log('📝 Next Steps:', 'cyan');
  log('   1. Test manually: http://localhost:9000/en/demo');
  log('   2. Select Nov 12, 2025');
  log('   3. Book appointment');
  log('   4. Check Supabase: npm run supabase:studio');
  log('   5. Verify appointment_date is 2025-11-12 (NOT 2025-11-11)\n');
}

testDateFormatting();
