const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');

// Test credentials
const TEST_EMAIL = 'tmartinez@gmail.com';
const TEST_PASSWORD = 'Skittles@420';
const BASE_URL = 'http://localhost:4321';

async function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function takeScreenshot(page, filename) {
  await page.screenshot({ 
    path: filename, 
    fullPage: true,
    type: 'png'
  });
  console.log(`Screenshot saved: ${filename}`);
}

async function checkConsoleErrors(page) {
  const logs = [];
  
  page.on('console', msg => {
    if (msg.type() === 'error') {
      logs.push(`Console Error: ${msg.text()}`);
    }
  });
  
  page.on('pageerror', error => {
    logs.push(`Page Error: ${error.message}`);
  });
  
  return logs;
}

async function login(page) {
  console.log('🔐 Logging in...');
  
  await page.goto(`${BASE_URL}/login`, { waitUntil: 'networkidle2' });
  await delay(2000);
  
  // Clear any existing session
  await page.evaluate(() => {
    localStorage.clear();
    sessionStorage.clear();
  });
  
  // Fill login form
  await page.waitForSelector('input[type="email"]', { timeout: 10000 });
  await page.type('input[type="email"]', TEST_EMAIL);
  await page.type('input[type="password"]', TEST_PASSWORD);
  
  // Submit form
  await page.click('button[type="submit"]');
  
  // Wait for redirect to dashboard
  await page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 15000 });
  
  console.log('✅ Login successful');
  return page.url().includes('/dashboard');
}

async function testRoute(browser, route, testName) {
  console.log(`\n🧪 Testing ${testName} (${route})`);
  
  const page = await browser.newPage();
  const errors = [];
  
  // Setup console error logging
  page.on('console', msg => {
    if (msg.type() === 'error') {
      errors.push(`Console Error: ${msg.text()}`);
    }
  });
  
  page.on('pageerror', error => {
    errors.push(`Page Error: ${error.message}`);
  });
  
  try {
    // Login first
    const loginSuccess = await login(page);
    if (!loginSuccess) {
      throw new Error('Login failed');
    }
    
    // Navigate to test route
    console.log(`Navigating to ${route}...`);
    await page.goto(`${BASE_URL}${route}`, { waitUntil: 'networkidle2' });
    await delay(3000);
    
    // Take screenshot
    const screenshotPath = `fixed-${testName.toLowerCase().replace(/\s+/g, '-')}.png`;
    await takeScreenshot(page, screenshotPath);
    
    // Get page content for analysis
    const title = await page.title();
    const url = page.url();
    const content = await page.content();
    
    console.log(`✅ ${testName} - Title: ${title}`);
    console.log(`   URL: ${url}`);
    
    if (errors.length > 0) {
      console.log(`⚠️  Errors found:`);
      errors.forEach(error => console.log(`   ${error}`));
    } else {
      console.log(`✅ No console errors`);
    }
    
    return {
      route,
      testName,
      title,
      url,
      errors,
      screenshotPath,
      success: true
    };
    
  } catch (error) {
    console.log(`❌ ${testName} failed: ${error.message}`);
    return {
      route,
      testName,
      title: null,
      url: null,
      errors: [...errors, error.message],
      screenshotPath: null,
      success: false
    };
  } finally {
    await page.close();
  }
}

async function testEventStatsAPI(browser) {
  console.log(`\n🧪 Testing Event Stats API`);
  
  const page = await browser.newPage();
  const errors = [];
  
  try {
    // Login first
    const loginSuccess = await login(page);
    if (!loginSuccess) {
      throw new Error('Login failed');
    }
    
    // Go to dashboard to get an event ID
    await page.goto(`${BASE_URL}/dashboard`, { waitUntil: 'networkidle2' });
    await delay(2000);
    
    // Try to find an event ID from the dashboard
    const eventLinks = await page.$$eval('a[href*="/events/"]', links => 
      links.map(link => link.href.match(/\/events\/([^\/]+)/)?.[1]).filter(Boolean)
    );
    
    if (eventLinks.length === 0) {
      console.log('⚠️  No events found to test API with');
      return {
        route: '/api/events/[id]/stats',
        testName: 'Event Stats API',
        success: false,
        errors: ['No events available to test']
      };
    }
    
    const eventId = eventLinks[0];
    console.log(`Testing API with event ID: ${eventId}`);
    
    // Test the API endpoint
    const response = await page.evaluate(async (eventId) => {
      try {
        const res = await fetch(`/api/events/${eventId}/stats`);
        return {
          status: res.status,
          statusText: res.statusText,
          data: await res.json()
        };
      } catch (error) {
        return {
          error: error.message
        };
      }
    }, eventId);
    
    console.log(`✅ Event Stats API - Status: ${response.status}`);
    console.log(`   Response:`, JSON.stringify(response.data, null, 2));
    
    return {
      route: `/api/events/${eventId}/stats`,
      testName: 'Event Stats API',
      response,
      success: response.status === 200,
      errors: response.error ? [response.error] : []
    };
    
  } catch (error) {
    console.log(`❌ Event Stats API failed: ${error.message}`);
    return {
      route: '/api/events/[id]/stats',
      testName: 'Event Stats API',
      success: false,
      errors: [error.message]
    };
  } finally {
    await page.close();
  }
}

async function runTests() {
  console.log('🚀 Starting Critical Fixes Verification Tests');
  console.log('='.repeat(50));
  
  const browser = await puppeteer.launch({
    headless: false,
    args: ['--no-sandbox', '--disable-setuid-sandbox'],
    defaultViewport: { width: 1280, height: 720 }
  });
  
  const results = [];
  
  // Test routes
  const routes = [
    { route: '/scan', testName: 'QR Scanner' },
    { route: '/templates', testName: 'Templates' },
    { route: '/calendar', testName: 'Calendar' }
  ];
  
  for (const { route, testName } of routes) {
    const result = await testRoute(browser, route, testName);
    results.push(result);
  }
  
  // Test Event Stats API
  const apiResult = await testEventStatsAPI(browser);
  results.push(apiResult);
  
  await browser.close();
  
  // Generate report
  console.log('\n📊 TEST RESULTS SUMMARY');
  console.log('='.repeat(50));
  
  const report = {
    timestamp: new Date().toISOString(),
    results: results,
    summary: {
      total: results.length,
      passed: results.filter(r => r.success).length,
      failed: results.filter(r => !r.success).length
    }
  };
  
  results.forEach(result => {
    const status = result.success ? '✅ PASS' : '❌ FAIL';
    console.log(`${status} ${result.testName}`);
    if (result.errors.length > 0) {
      result.errors.forEach(error => console.log(`   ⚠️  ${error}`));
    }
  });
  
  // Save detailed report
  fs.writeFileSync('critical-fixes-test-report.json', JSON.stringify(report, null, 2));
  console.log('\n📄 Detailed report saved to: critical-fixes-test-report.json');
  
  console.log(`\n🎯 Overall Result: ${report.summary.passed}/${report.summary.total} tests passed`);
}

// Run tests
runTests().catch(console.error);