/**
 * Debug TEC Form Access
 * 
 * Tests different TEC Community Events URLs to find the correct form access point
 */

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

async function debugTecFormAccess() {
    console.log('🔍 Debugging TEC Form Access...');
    
    const browser = await chromium.launch({ 
        headless: true,
        slowMo: 500
    });
    
    try {
        const context = await browser.newContext({
            viewport: { width: 1200, height: 800 }
        });
        
        const page = await context.newPage();
        
        // Enable console logging
        page.on('console', msg => {
            if (msg.type() === 'log' || msg.type() === 'error') {
                console.log(`🖥️  ${msg.text()}`);
            }
        });
        
        // Test different TEC URLs
        const testUrls = [
            'https://upskill-staging.measurequick.com/?events-community=add',
            'https://upskill-staging.measurequick.com/events/community/add/',
            'https://upskill-staging.measurequick.com/events-community/add/',
            'https://upskill-staging.measurequick.com/add-event/',
            'https://upskill-staging.measurequick.com/event/add/',
            'https://upskill-staging.measurequick.com/events/add/',
            'https://upskill-staging.measurequick.com/submit-event/'
        ];
        
        for (const url of testUrls) {
            console.log(`\n🌐 Testing URL: ${url}`);
            
            try {
                await page.goto(url);
                await page.waitForTimeout(2000);
                
                // Check page title
                const title = await page.title();
                console.log(`📄 Page Title: ${title}`);
                
                // Check for TEC form elements
                const tecSelectors = [
                    '#tribe-community-events-form',
                    '.tribe-community-events',
                    '#tribe-events-community-edit-form',
                    'form[data-datepicker_format]',
                    '[name="post_title"]',
                    '[name="post_content"]'
                ];
                
                let foundForm = false;
                for (const selector of tecSelectors) {
                    try {
                        const element = await page.waitForSelector(selector, { timeout: 1000 });
                        if (element) {
                            console.log(`✅ Found TEC form element: ${selector}`);
                            foundForm = true;
                            break;
                        }
                    } catch (e) {
                        // Continue to next selector
                    }
                }
                
                if (!foundForm) {
                    console.log('❌ No TEC form elements found');
                    
                    // Check for error messages or redirects
                    const bodyText = await page.textContent('body');
                    if (bodyText.includes('404') || bodyText.includes('not found')) {
                        console.log('🔴 Page shows 404 error');
                    } else if (bodyText.includes('permission') || bodyText.includes('access')) {
                        console.log('🔴 Permission/access issue');
                    } else if (bodyText.includes('login') || bodyText.includes('sign in')) {
                        console.log('🔴 Login required');
                    } else {
                        console.log('🟡 Page loads but no TEC form found');
                    }
                } else {
                    // Found the form! Test for enhanced template
                    console.log('🎯 TEC Form Found! Testing for enhanced template...');
                    
                    // Check for enhanced template indicator
                    try {
                        const enhancedIndicator = await page.waitForSelector('.hvac-success-indicator', { timeout: 2000 });
                        if (enhancedIndicator) {
                            const indicatorText = await enhancedIndicator.textContent();
                            console.log(`🚀 Enhanced template active: ${indicatorText}`);
                        }
                    } catch (e) {
                        console.log('⚠️  Enhanced template indicator not found - standard template in use');
                    }
                    
                    // Take screenshot of working form
                    await page.screenshot({ 
                        path: `/home/ben/dev/upskill-event-manager/test-results/tec-form-found-${Date.now()}.png`,
                        fullPage: true 
                    });
                    
                    console.log('📸 Screenshot saved of working TEC form');
                    
                    return {
                        success: true,
                        workingUrl: url,
                        title: title
                    };
                }
                
            } catch (error) {
                console.log(`❌ URL failed: ${error.message}`);
            }
        }
        
        // If we get here, no working URLs found
        console.log('\n❌ No working TEC form URLs found');
        
        // Try to find the correct URL by checking main pages
        console.log('\n🔍 Checking main site for TEC links...');
        await page.goto('https://upskill-staging.measurequick.com/');
        await page.waitForTimeout(2000);
        
        // Look for add event links
        const addEventLinks = await page.$$eval('a', links => 
            links.filter(link => 
                link.textContent.toLowerCase().includes('add') ||
                link.textContent.toLowerCase().includes('submit') ||
                link.textContent.toLowerCase().includes('create') ||
                link.href.includes('event')
            ).map(link => ({ text: link.textContent, href: link.href }))
        );
        
        if (addEventLinks.length > 0) {
            console.log('🔗 Found potential event links:');
            addEventLinks.forEach(link => {
                console.log(`   - ${link.text}: ${link.href}`);
            });
        }
        
        return {
            success: false,
            error: 'No TEC form found at any tested URL',
            potentialLinks: addEventLinks
        };
        
    } catch (error) {
        console.error('❌ Debug failed:', error);
        return { success: false, error: error.message };
    } finally {
        await browser.close();
    }
}

// Run the debug
if (require.main === module) {
    debugTecFormAccess()
        .then(result => {
            console.log('\n🏁 TEC Form Access Debug Complete');
            if (result.success) {
                console.log(`✅ Working URL found: ${result.workingUrl}`);
            } else {
                console.log('❌ No working TEC form URL found');
                console.log('💡 Suggestions:');
                console.log('   1. Check if TEC Community Events plugin is active');
                console.log('   2. Verify user has permission to submit events');
                console.log('   3. Check TEC plugin settings for form URLs');
                console.log('   4. Login as an authorized user first');
            }
            process.exit(result.success ? 0 : 1);
        })
        .catch(error => {
            console.error('❌ Debug runner failed:', error);
            process.exit(1);
        });
}

module.exports = { debugTecFormAccess };