/**
 * E2E Test: Demo Booking Date Bug Fix
 *
 * Tests that appointments are saved with the CORRECT date
 * (not one day earlier due to timezone conversion)
 */

import { test, expect } from '@playwright/test';

test.describe('Demo Booking Date Fix', () => {
  test('should save appointment on the selected date, not one day earlier', async ({ page }) => {
    // Navigate to demo booking page
    await page.goto('http://localhost:9000/en/demo');

    // Wait for page to load
    await page.waitForLoadState('networkidle');

    // Generate unique test email
    const testEmail = `date-test-${Date.now()}@test.com`;

    // ========================================
    // Select a specific date (Nov 12, 2025)
    // ========================================
    const targetDate = new Date(2025, 10, 12); // Nov 12, 2025 (month is 0-indexed)
    const expectedDateString = '2025-11-12'; // What we expect in database

    console.log('📅 Selecting date:', targetDate.toDateString());
    console.log('📅 Expected in DB:', expectedDateString);

    // Find and click the date picker
    const datePicker = page.locator('input[type="date"]').first();
    await datePicker.waitFor({ state: 'visible' });

    // Set the date value directly (YYYY-MM-DD format)
    await datePicker.fill(expectedDateString);

    // Small delay to ensure date is set
    await page.waitForTimeout(500);

    // Verify the date was set correctly in the input
    const dateInputValue = await datePicker.inputValue();
    console.log('✅ Date input value:', dateInputValue);
    expect(dateInputValue).toBe(expectedDateString);

    // ========================================
    // Select time slot
    // ========================================
    await page.waitForTimeout(500);

    // Click on a time slot (10:00 AM)
    const timeSlot = page.locator('button:has-text("10:00")').first();
    await timeSlot.waitFor({ state: 'visible', timeout: 5000 });
    await timeSlot.click();

    console.log('✅ Selected time: 10:00');

    // ========================================
    // Fill user information
    // ========================================
    await page.waitForTimeout(500);

    await page.fill('input[placeholder*="name" i]', 'Test User Date Fix');
    await page.fill('input[type="email"]', testEmail);
    await page.fill('input[type="tel"]', '+966501234567');

    // Fill special requirements if field exists
    const messageField = page.locator('textarea, input[placeholder*="requirement" i]').first();
    if (await messageField.count() > 0) {
      await messageField.fill('Testing date fix - appointment should be on Nov 12');
    }

    console.log('✅ Filled user information');

    // ========================================
    // Submit the form
    // ========================================
    await page.waitForTimeout(500);

    // Click submit button
    const submitButton = page.locator('button[type="submit"], button:has-text("Book"), button:has-text("Submit")').first();
    await submitButton.waitFor({ state: 'visible' });

    console.log('📤 Submitting booking form...');
    await submitButton.click();

    // Wait for submission to complete (success message or redirect)
    await page.waitForTimeout(3000);

    // ========================================
    // Verify in database
    // ========================================
    console.log('🔍 Verifying date in database...');

    // Query Supabase via API
    const response = await page.request.get('http://127.0.0.1:54321/rest/v1/demo_bookings', {
      params: {
        email: `eq.${testEmail}`,
        select: 'appointment_date,full_name,email',
      },
      headers: {
        'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0',
        'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0',
      },
    });

    const bookings = await response.json();
    console.log('📊 Database result:', JSON.stringify(bookings, null, 2));

    expect(bookings.length).toBeGreaterThan(0);

    const savedBooking = bookings[0];
    const savedDate = savedBooking.appointment_date;

    // Extract date part from timestamp
    const savedDateOnly = savedDate.split('T')[0];

    console.log('📅 User selected date:', expectedDateString);
    console.log('💾 Database saved date:', savedDateOnly);

    // CRITICAL ASSERTION: Dates must match!
    expect(savedDateOnly).toBe(expectedDateString);

    if (savedDateOnly === expectedDateString) {
      console.log('✅ SUCCESS! Date saved correctly without timezone shift!');
    } else {
      console.log('❌ FAILURE! Date still has timezone bug:');
      console.log(`   Expected: ${expectedDateString}`);
      console.log(`   Got: ${savedDateOnly}`);
      throw new Error(`Date mismatch: expected ${expectedDateString}, got ${savedDateOnly}`);
    }

    // Cleanup: Delete test booking
    await page.request.delete('http://127.0.0.1:54321/rest/v1/demo_bookings', {
      params: {
        email: `eq.${testEmail}`,
      },
      headers: {
        'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU',
        'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU',
      },
    });

    console.log('🧹 Test booking cleaned up');
  });

  test('should handle dates correctly across different timezones', async ({ page }) => {
    // Test multiple dates to ensure consistency
    const testDates = [
      { date: '2025-11-15', label: 'Nov 15' },
      { date: '2025-12-01', label: 'Dec 1' },
      { date: '2025-12-25', label: 'Dec 25' },
    ];

    for (const testDate of testDates) {
      const testEmail = `timezone-test-${Date.now()}-${testDate.date}@test.com`;

      await page.goto('http://localhost:9000/en/demo');
      await page.waitForLoadState('networkidle');

      // Select date
      const datePicker = page.locator('input[type="date"]').first();
      await datePicker.fill(testDate.date);
      await page.waitForTimeout(500);

      // Select time
      const timeSlot = page.locator('button:has-text("14:00")').first();
      await timeSlot.click();
      await page.waitForTimeout(500);

      // Fill form
      await page.fill('input[placeholder*="name" i]', `Test ${testDate.label}`);
      await page.fill('input[type="email"]', testEmail);
      await page.fill('input[type="tel"]', '+966501234567');

      // Submit
      const submitButton = page.locator('button[type="submit"]').first();
      await submitButton.click();
      await page.waitForTimeout(2000);

      // Verify in database
      const response = await page.request.get('http://127.0.0.1:54321/rest/v1/demo_bookings', {
        params: {
          email: `eq.${testEmail}`,
          select: 'appointment_date',
        },
        headers: {
          'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0',
          'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0',
        },
      });

      const bookings = await response.json();
      const savedDateOnly = bookings[0]?.appointment_date?.split('T')[0];

      console.log(`${testDate.label}: Expected ${testDate.date}, Got ${savedDateOnly}`);
      expect(savedDateOnly).toBe(testDate.date);

      // Cleanup
      await page.request.delete('http://127.0.0.1:54321/rest/v1/demo_bookings', {
        params: { email: `eq.${testEmail}` },
        headers: {
          'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU',
          'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU',
        },
      });
    }

    console.log('✅ All timezone tests passed!');
  });
});
