/**
 * Test Both Durations (30min and 1hr) Work Correctly
 * Prevents regression of duration format mismatch
 */

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

// Test both 30 min and 60 min durations
for (const duration of [{ label: '30 minutes', value: '30min' }, { label: '60 minutes (1 hour)', value: '1hr' }]) {
  test(`should accept ${duration.value} duration and save to database`, async ({ page }) => {
    test.setTimeout(90000);

    const testEmail = `test-${duration.value}-${Date.now()}@mawidi.com`;
    console.log(`\n🧪 Testing ${duration.value} duration\n`);

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

    // Wait for cookie auto-dismiss or click accept
    await page.waitForTimeout(9000);

    // Select duration
    const durationBtn = page.getByRole('button', { name: new RegExp(duration.label, 'i') });
    await durationBtn.click();
    await page.waitForTimeout(500);

    // Next
    await page.getByRole('button', { name: 'Next', exact: true }).click();
    await page.waitForTimeout(1500);

    // Select tomorrow
    const tomorrow = page.locator('button:has-text("Tomorrow")').first();
    await tomorrow.click();
    await page.waitForTimeout(1000);

    // Select first available time
    const timeSlot = page.locator('button[aria-label*="PM"]:not([disabled]):not([title*="Too soon"])').first();
    await timeSlot.click();
    await page.waitForTimeout(500);

    // Next
    await page.getByRole('button', { name: 'Next', exact: true }).click();
    await page.waitForTimeout(1500);

    // Fill form
    await page.locator('input').first().fill('Test User');
    await page.locator('input[type="email"]').fill(testEmail);
    await page.locator('input[type="tel"]').fill('+966501234567');
    await page.locator('textarea').fill('Test booking');

    // Next
    await page.getByRole('button', { name: 'Next', exact: true }).click();
    await page.waitForTimeout(1500);

    // Listen for API call
    const responsePromise = page.waitForResponse(
      res => res.url().includes('/api/demo/book'),
      { timeout: 20000 }
    );

    // Click Confirm
    console.log(`   Clicking Confirm Booking for ${duration.value}...`);
    await page.getByRole('button', { name: /Confirm Booking/i }).click();

    // Wait for response
    const apiResponse = await responsePromise;
    const status = apiResponse.status();
    const body = await apiResponse.json();

    console.log(`   API Status: ${status}`);
    console.log(`   API Body:`, body);

    // Verify success
    expect(status).toBe(201);
    expect(body.success).toBe(true);
    expect(body.bookingId).toBeTruthy();

    // Wait for success screen
    await page.waitForTimeout(2000);

    // Verify success page
    const successText = await page.textContent('body');
    expect(successText).toMatch(/success|confirmed|booking/i);

    // Verify booking reference visible
    expect(successText).toContain(body.bookingId);

    console.log(`   ✅ ${duration.value} booking SUCCESS!`);
    console.log(`   Booking ID: ${body.bookingId}`);

    // Verify in database
    const dbResponse = await fetch(
      `http://127.0.0.1:54321/rest/v1/demo_bookings?select=*&id=eq.${body.bookingId}`,
      {
        headers: {
          apikey: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU',
          Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU',
        },
      }
    );

    const dbData = await dbResponse.json();
    expect(dbData.length).toBe(1);
    expect(dbData[0].duration).toBe(duration.value);
    expect(dbData[0].telephone).toBe('+966501234567');

    console.log(`   ✅ Verified in database with duration: ${dbData[0].duration}`);

    // Cleanup
    await fetch(`http://127.0.0.1:54321/rest/v1/demo_bookings?id=eq.${body.bookingId}`, {
      method: 'DELETE',
      headers: {
        apikey: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU',
        Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU',
      },
    });

    console.log(`   🧹 Cleaned up test booking\n`);
  });
}
