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

async function testAdminDetection() {
  console.log('🧪 Testing admin detection...');
  
  const browser = await chromium.launch({ 
    headless: false,
    slowMo: 1000
  });
  
  const context = await browser.newContext({
    viewport: { width: 1280, height: 720 }
  });
  
  const page = await context.newPage();
  
  // Enable console logging
  page.on('console', msg => console.log(`[PAGE] ${msg.text()}`));
  page.on('response', response => {
    if (response.url().includes('/api/auth') || response.url().includes('/admin')) {
      console.log(`[API] ${response.status()} ${response.url()}`);
    }
  });
  
  try {
    // First login
    console.log('\n🔑 Step 1: Logging in...');
    await page.goto('http://localhost:3000/login-new', { waitUntil: 'networkidle' });
    
    await page.fill('#email', 'tmartinez@gmail.com');
    await page.fill('#password', 'Skittles@420');
    await page.click('button[type="submit"]');
    
    // Wait for login to complete
    await page.waitForTimeout(5000);
    console.log(`After login: ${page.url()}`);
    
    // Test auth endpoints with the logged-in session
    console.log('\n🔍 Step 2: Testing auth endpoints...');
    
    // Test auth user endpoint
    const userResponse = await page.goto('http://localhost:3000/api/auth/user');
    const userData = await userResponse.json();
    console.log('User data:', userData);
    
    // Test admin auth check endpoint  
    const adminResponse = await page.goto('http://localhost:3000/api/admin/auth-check');
    const adminData = await adminResponse.json();
    console.log('Admin auth data:', adminData);
    
    // Go back to dashboard and manually run the navigation script
    console.log('\n🔧 Step 3: Testing navigation script...');
    await page.goto('http://localhost:3000/dashboard', { waitUntil: 'networkidle' });
    await page.waitForTimeout(3000);
    
    // Execute the admin detection logic manually
    const adminDetected = await page.evaluate(async () => {
      try {
        console.log('[NAV DEBUG] Starting manual admin detection...');
        
        // Try server-side API call
        const response = await fetch('/api/auth/user');
        console.log('[NAV DEBUG] Auth user response status:', response.status);
        
        if (response.ok) {
          const userData = await response.json();
          console.log('[NAV DEBUG] User data from API:', userData);
          return userData.isAdmin === true;
        } else {
          console.log('[NAV DEBUG] Auth user API failed');
          return false;
        }
      } catch (error) {
        console.error('[NAV DEBUG] Error in admin detection:', error);
        return false;
      }
    });
    
    console.log(`Manual admin detection result: ${adminDetected}`);
    
    if (adminDetected) {
      console.log('✅ Admin detected - menu items should be visible');
    } else {
      console.log('❌ Admin not detected - checking why...');
      
      // Let's also test the admin auth check endpoint
      const adminCheck = await page.evaluate(async () => {
        try {
          const response = await fetch('/api/admin/auth-check');
          console.log('[NAV DEBUG] Admin auth check status:', response.status);
          if (response.ok) {
            const data = await response.json();
            console.log('[NAV DEBUG] Admin auth check data:', data);
            return data;
          }
          return null;
        } catch (error) {
          console.error('[NAV DEBUG] Admin auth check failed:', error);
          return null;
        }
      });
      
      console.log('Admin auth check result:', adminCheck);
    }
    
  } catch (error) {
    console.error('❌ Test failed:', error);
    await page.screenshot({ path: 'admin-detection-error.png' });
  } finally {
    await browser.close();
  }
}

testAdminDetection().catch(console.error);