const { chromium } = require('playwright');

async function testStatsAPI() {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext();
  const page = await context.newPage();
  
  try {
    console.log('🔑 Authenticating...');
    
    // Login first
    await page.goto('http://192.168.0.46:3000/login-new');
    await page.waitForTimeout(1000);
    
    // Accept cookies
    const cookieBanner = await page.$('#cookie-consent-banner');
    if (cookieBanner) {
      await page.click('#cookie-accept-btn');
      await page.waitForTimeout(500);
    }
    
    await page.fill('#email', 'tmartinez@gmail.com');
    await page.fill('#password', 'TestPassword123!');
    await page.click('#login-btn');
    await page.waitForTimeout(3000);
    
    console.log('✅ Authenticated');
    
    console.log('\n🧪 Testing stats API directly...');
    
    // Test the stats API endpoint directly
    const statsUrl = 'http://192.168.0.46:3000/api/events/7ac12bd2-8509-4db3-b1bc-98a808646311/stats';
    
    const response = await page.evaluate(async (url) => {
      try {
        const res = await fetch(url, {
          method: 'GET',
          credentials: 'include', // Include cookies
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const text = await res.text();
        
        return {
          status: res.status,
          statusText: res.statusText,
          headers: Object.fromEntries(res.headers.entries()),
          body: text,
          ok: res.ok
        };
      } catch (error) {
        return {
          error: error.message,
          status: 0
        };
      }
    }, statsUrl);
    
    console.log('📊 Stats API Response:');
    console.log('Status:', response.status);
    console.log('OK:', response.ok);
    console.log('Body:', response.body);
    
    if (!response.ok) {
      console.log('❌ Stats API failed');
      
      // Try to get more details from the server logs
      console.log('\n🔍 Checking server logs...');
      
      // Navigate to a page that might show server errors
      await page.goto('http://192.168.0.46:3000/events/7ac12bd2-8509-4db3-b1bc-98a808646311', { 
        waitUntil: 'networkidle' 
      });
      await page.waitForTimeout(2000);
      
    } else {
      console.log('✅ Stats API working!');
      
      // Parse the JSON response
      try {
        const data = JSON.parse(response.body);
        console.log('📈 Stats data:', data);
      } catch (error) {
        console.log('⚠️  Response is not valid JSON');
      }
    }
    
  } catch (error) {
    console.error('💥 Test failed:', error);
  } finally {
    await browser.close();
  }
}

testStatsAPI();