import { STAGING_URL, PATHS, TIMEOUTS } from './config/staging-config';
import { test, expect, Page } from '@playwright/test';
import * as dotenv from 'dotenv';
import { resolve } from 'path';

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

test.use({
  screenshot: 'only-on-failure',
  video: 'retain-on-failure',
  trace: 'retain-on-failure',
  actionTimeout: 30000,
  timeout: 120000, // 2 minutes per test
});

test.describe('Event Creation via API', () => {
  const stagingUrl = process.env.UPSKILL_STAGING_URL || 'https://upskill-staging.measurequick.com';
  
  test('creates event via WordPress AJAX API', async ({ page, request }) => {
    const username = 'test_trainer';
    const password = 'Test123!';

    // Step 1: Login to get cookies and nonce
    await page.goto(stagingUrl + '/community-login/', { waitUntil: 'domcontentloaded' });
    await page.fill('input#user_login', username);
    await page.fill('input#user_pass', password);
    await page.getByRole('button', { name: /log in/i }).click();
    await page.waitForURL(/hvac-dashboard|manage-event/, { timeout: 30000 });

    // Get the cookies from the logged-in session
    const cookies = await page.context().cookies();
    
    // Navigate to the event creation page to get the nonce
    await page.goto(stagingUrl + '/manage-event/', { waitUntil: 'domcontentloaded' });
    
    // Extract nonce and form data from the page
    const formData = await page.evaluate(() => {
      const form = document.querySelector('form');
      if (!form) return null;
      
      // Get nonce values
      const nonceInput = document.querySelector('input[name="_wpnonce"]') as HTMLInputElement;
      const nonce = nonceInput?.value || '';
      
      // Get any other hidden fields
      const hiddenInputs: Record<string, string> = {};
      form.querySelectorAll('input[type="hidden"]').forEach((input) => {
        const name = (input as HTMLInputElement).name;
        const value = (input as HTMLInputElement).value;
        if (name) hiddenInputs[name] = value;
      });
      
      return { nonce, hiddenInputs };
    });

    if (!formData) {
      throw new Error('Could not extract form data');
    }

    // Step 2: Create event via AJAX
    const now = new Date();
    const uniqueTitle = `HVAC Training ${now.toISOString().split('.')[0].replace(/[-T:]/g, '')}`;
    const eventDate = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
    const dateStr = eventDate.toISOString().split('T')[0];
    
    // Build the request data
    const eventData = {
      post_title: uniqueTitle,
      post_content: `This is a test event created on ${now.toISOString()}. This event covers HVAC training basics.`,
      tcepostcontent: `This is a test event created on ${now.toISOString()}. This event covers HVAC training basics.`,
      EventStartDate: dateStr,
      EventEndDate: dateStr,
      EventStartTime: '09:00',
      EventEndTime: '17:00',
      'venue[Venue]': 'New Test Venue',
      'venue[Address]': '789 Test St',
      'venue[City]': 'Test City',
      'venue[Province]': 'BC',
      'venue[Country]': 'Canada',
      'venue[Zip]': 'V1X 1X1',
      EventOrganizerID: '0',
      ticket_price: '100',
      ticket_quantity: '20',
      _wpnonce: formData.nonce,
      ...formData.hiddenInputs
    };

    // Try direct form submission via AJAX
    const response = await request.post(stagingUrl + '/wp-admin/admin-ajax.php', {
      headers: {
        'Cookie': cookies.map(c => `${c.name}=${c.value}`).join('; '),
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      form: {
        action: 'tribe_events_community_save',
        ...eventData
      }
    });

    const responseText = await response.text();
    console.log('AJAX Response:', responseText);

    // If AJAX doesn't work, try direct POST to the form action
    if (!response.ok || responseText.includes('error')) {
      const formAction = await page.getAttribute('form', 'action') || stagingUrl + '/manage-event/';
      
      const directResponse = await request.post(formAction, {
        headers: {
          'Cookie': cookies.map(c => `${c.name}=${c.value}`).join('; '),
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        form: eventData
      });

      console.log('Direct POST response status:', directResponse.status());
      const directResponseText = await directResponse.text();
      
      if (directResponseText.includes(uniqueTitle) || directResponseText.includes('Event submitted')) {
        console.log('Event created successfully via direct POST!');
      } else {
        throw new Error('Event creation failed via API');
      }
    }
  });

  test('creates event via REST API', async ({ page, request }) => {
    const username = 'test_trainer';
    const password = 'Test123!';

    // Step 1: Login to get authentication token
    await page.goto(stagingUrl + '/community-login/', { waitUntil: 'domcontentloaded' });
    await page.fill('input#user_login', username);
    await page.fill('input#user_pass', password);
    await page.getByRole('button', { name: /log in/i }).click();
    await page.waitForURL(/hvac-dashboard|manage-event/, { timeout: 30000 });

    // Get cookies for authentication
    const cookies = await page.context().cookies();
    
    // Try the REST API
    const now = new Date();
    const uniqueTitle = `HVAC Training ${now.toISOString().split('.')[0].replace(/[-T:]/g, '')}`;
    const eventDate = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
    
    // REST API payload based on The Events Calendar documentation
    const eventPayload = {
      title: uniqueTitle,
      description: `This is a test event created on ${now.toISOString()}. This event covers HVAC training basics.`,
      start_date: eventDate.toISOString(),
      end_date: eventDate.toISOString(),
      venue: {
        venue: 'New Test Venue',
        address: '789 Test St',
        city: 'Test City',
        province: 'BC',
        country: 'Canada',
        zip: 'V1X 1X1'
      }
    };

    try {
      // Try the official TEC REST API endpoint
      const response = await request.post(stagingUrl + '/wp-json/tribe/events/v1/events', {
        headers: {
          'Cookie': cookies.map(c => `${c.name}=${c.value}`).join('; '),
          'Content-Type': 'application/json'
        },
        data: eventPayload
      });

      const responseData = await response.json();
      console.log('REST API Response:', JSON.stringify(responseData, null, 2));

      if (response.ok && responseData.id) {
        console.log('Event created successfully via REST API!');
        console.log('Event ID:', responseData.id);
      } else {
        console.error('REST API failed:', responseData);
      }
    } catch (error) {
      console.error('REST API error:', error);
    }
  });
});