/**
 * Detailed debugging to understand the redirect behavior
 */

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

async function testDetailedDebug() {
    console.log('🔍 Testing Detailed Debug...\\n');
    
    const browser = await chromium.launch({
        headless: false,
        args: ['--disable-dev-shm-usage', '--no-sandbox']
    });
    
    const context = await browser.newContext({
        viewport: { width: 1280, height: 720 }
    });
    
    const page = await context.newPage();
    const baseUrl = 'https://upskill-staging.measurequick.com';
    
    // Track all requests and responses
    const requests = [];
    const responses = [];
    
    page.on('request', request => {
        requests.push({
            url: request.url(),
            method: request.method(),
            headers: request.headers()
        });
        console.log(`📤 REQUEST: ${request.method()} ${request.url()}`);
    });
    
    page.on('response', response => {
        responses.push({
            url: response.url(),
            status: response.status(),
            headers: response.headers()
        });
        console.log(`📥 RESPONSE: ${response.status()} ${response.url()}`);
        if (response.status() >= 300 && response.status() < 400) {
            console.log(`🔄 REDIRECT: ${response.status()} - Location: ${response.headers()['location'] || 'Not specified'}`);
        }
    });
    
    try {
        // Step 1: Login first
        console.log('1️⃣ Logging in...');
        await page.goto(`${baseUrl}/training-login/`);
        await page.waitForLoadState('networkidle');
        
        // Wait for form to be visible
        await page.waitForSelector('input[name="log"]', { timeout: 10000 });
        
        console.log('   Filling login form...');
        await page.fill('input[name="log"]', 'test_trainer');
        await page.fill('input[name="pwd"]', 'TestTrainer123!');
        
        // Try different submission methods
        const submitButton = await page.$('input[type="submit"]');
        const form = await page.$('form#loginform, form.wp-form');
        
        console.log('   Submit button found:', !!submitButton);
        console.log('   Form found:', !!form);
        
        if (submitButton) {
            console.log('   Clicking submit button...');
            await Promise.all([
                page.waitForNavigation({ waitUntil: 'networkidle', timeout: 15000 }),
                submitButton.click()
            ]);
        } else if (form) {
            console.log('   Submitting form...');
            await Promise.all([
                page.waitForNavigation({ waitUntil: 'networkidle', timeout: 15000 }),
                form.evaluate(form => form.submit())
            ]);
        } else {
            console.log('   Trying Enter key...');
            await page.press('input[name="pwd"]', 'Enter');
            await page.waitForNavigation({ waitUntil: 'networkidle', timeout: 15000 });
        }
        
        const afterLoginUrl = page.url();
        console.log('✅ Logged in - Current URL:', afterLoginUrl);
        
        // Check login status
        console.log('\\n2️⃣ Checking login status...');
        const loginStatus = await page.evaluate(() => {
            // Check for login indicators
            const body = document.body.innerHTML;
            const hasLogoutLink = body.includes('logout') || body.includes('Logout');
            const hasLoginForm = body.includes('name="log"') && body.includes('name="pwd"');
            
            return {
                hasLogoutLink,
                hasLoginForm,
                bodySnippet: body.substring(0, 500)
            };
        });
        
        console.log('   Has logout link:', loginStatus.hasLogoutLink);
        console.log('   Has login form:', loginStatus.hasLoginForm);
        
        if (loginStatus.hasLoginForm) {
            console.log('❌ Still on login page - authentication failed');
            await page.screenshot({ path: `auth-failed-${Date.now()}.png` });
            return;
        }
        
        // Wait a moment for any auth cookies to settle
        await page.waitForTimeout(2000);
        
        // Step 3: Navigate to edit page and track redirects
        console.log('\\n3️⃣ Navigating to edit page...');
        const targetUrl = `${baseUrl}/trainer/event/edit/?event_id=6161`;
        console.log('   Target URL:', targetUrl);
        
        // Clear request/response arrays
        requests.length = 0;
        responses.length = 0;
        
        await page.goto(targetUrl, { waitUntil: 'networkidle' });
        
        const finalUrl = page.url();
        console.log('   Final URL:', finalUrl);
        
        // Analyze the redirect chain
        console.log('\\n4️⃣ Redirect Analysis:');
        const redirectChain = responses.filter(r => r.status >= 300 && r.status < 400);
        
        if (redirectChain.length > 0) {
            console.log(`   Found ${redirectChain.length} redirects:`);
            redirectChain.forEach((redirect, index) => {
                console.log(`   ${index + 1}. ${redirect.status} - ${redirect.url}`);
                if (redirect.headers['location']) {
                    console.log(`      → Location: ${redirect.headers['location']}`);
                }
            });
        } else {
            console.log('   No redirects detected');
        }
        
        // Check final page content
        console.log('\\n5️⃣ Final Page Analysis:');
        const pageAnalysis = await page.evaluate(() => {
            const title = document.title;
            const hasLoginForm = document.querySelector('input[name="log"]') !== null;
            const hasEventForm = document.querySelector('.hvac-event-form') !== null;
            const hasCustomTemplate = document.body.innerHTML.includes('Custom Event Edit Template Loaded Successfully');
            const mainContent = document.querySelector('#main, .site-main, [role="main"]');
            
            return {
                title,
                hasLoginForm,
                hasEventForm,
                hasCustomTemplate,
                mainContentSnippet: mainContent ? mainContent.innerHTML.substring(0, 300) : 'Main content not found'
            };
        });
        
        console.log('   Page title:', pageAnalysis.title);
        console.log('   Has login form:', pageAnalysis.hasLoginForm);
        console.log('   Has event form:', pageAnalysis.hasEventForm);
        console.log('   Has custom template marker:', pageAnalysis.hasCustomTemplate);
        console.log('   Main content snippet:', pageAnalysis.mainContentSnippet);
        
        // Take screenshot
        await page.screenshot({ 
            path: `detailed-debug-${Date.now()}.png`,
            fullPage: true 
        });
        console.log('\\n📸 Screenshot saved');
        
    } catch (error) {
        console.error('\\n❌ Test failed:', error.message);
        
        await page.screenshot({ 
            path: `error-detailed-${Date.now()}.png`,
            fullPage: true 
        });
    } finally {
        console.log('\\n⏸️ Keeping browser open for inspection...');
        await page.waitForTimeout(10000);
        await browser.close();
    }
}

// Run test
testDetailedDebug()
    .then(() => {
        console.log('\\n✨ Test completed!');
        process.exit(0);
    })
    .catch(error => {
        console.error('\\n💥 Test failed:', error);
        process.exit(1);
    });