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

async function testCsvRemigration() {
    console.log('🔄 TESTING CSV RE-MIGRATION');
    console.log('================================================================================');
    
    const browser = await chromium.launch({ headless: false });
    const context = await browser.newContext();
    const page = await context.newPage();
    
    try {
        // Login as master trainer
        console.log('📝 Logging in as master trainer...');
        await page.goto('https://upskill-staging.measurequick.com/wp-login.php');
        await page.fill('#user_login', 'JoeMedosch@gmail.com');
        await page.fill('#user_pass', 'JoeTrainer2025@');
        await page.click('#wp-submit');
        await page.waitForURL('**/master-trainer/master-dashboard/**', { timeout: 15000 });
        console.log('✅ Master trainer login successful');
        
        // Go to a page with AJAX access
        await page.goto('https://upskill-staging.measurequick.com/trainer/profile/');
        await page.waitForLoadState('networkidle');
        
        // Execute the re-migration via AJAX
        console.log('🔄 Running CSV re-migration via AJAX...');
        console.log('⏱️ This may take several minutes...');
        
        const remigrationResult = await page.evaluate(async () => {
            try {
                const response = await fetch(hvac_ajax.ajax_url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'hvac_remigrate_csv_data',
                        nonce: hvac_ajax.nonce
                    })
                });
                
                const data = await response.json();
                return data;
            } catch (e) {
                return { success: false, error: 'Exception: ' + e.message };
            }
        });
        
        console.log('📋 Re-migration result:', remigrationResult);
        
        if (remigrationResult.success) {
            const results = remigrationResult.data;
            console.log('\n🎉 CSV RE-MIGRATION COMPLETED SUCCESSFULLY!');
            console.log('================================================================================');
            console.log(`📊 SUMMARY:`);
            console.log(`   Total Import Sessions: ${results.total_sessions}`);
            console.log(`   Profiles Processed: ${results.profiles_processed}`);
            console.log(`   Profiles Updated: ${results.profiles_updated}`);
            console.log(`   Total Fields Updated: ${results.fields_updated}`);
            console.log(`   Geocoding Scheduled: ${results.geocoding_scheduled}`);
            console.log(`   Errors: ${results.errors}`);
            console.log(`   Duration: ${results.duration} seconds`);
            
            if (results.details && results.details.length > 0) {
                console.log('\n📍 PROFILE UPDATE DETAILS:');
                let updateCount = 0;
                results.details.forEach(detail => {
                    if (detail.status === 'updated' && detail.fields_updated > 0) {
                        updateCount++;
                        if (updateCount <= 10) { // Show first 10 updates
                            const geocodingStatus = detail.geocoding_scheduled ? '🗺️ Geocoding scheduled' : '';
                            console.log(`   ✅ ${detail.name || detail.email} - ${detail.fields_updated} fields updated ${geocodingStatus}`);
                        }
                    }
                });
                
                if (updateCount > 10) {
                    console.log(`   ... and ${updateCount - 10} more profiles updated`);
                }
                
                // Show any errors
                const errorDetails = results.details.filter(d => d.status === 'error');
                if (errorDetails.length > 0) {
                    console.log('\n❌ ERRORS:');
                    errorDetails.forEach(detail => {
                        console.log(`   ❌ ${detail.email}: ${detail.error}`);
                    });
                }
            }
            
        } else {
            console.log('\n❌ CSV RE-MIGRATION FAILED:');
            console.log('   Error:', remigrationResult.data || remigrationResult.error);
        }
        
        // If that doesn't work, let's execute it differently by checking current profile data
        console.log('\n🔍 Checking current profile data to verify if location fields exist...');
        
        const profileCheck = await page.evaluate(() => {
            // Look for location indicators in the current profile page
            const profileContent = document.body.innerText;
            
            // Check if we can see location data in the current profile
            const hasLocationSection = profileContent.includes('Location:') || 
                                     profileContent.includes('City') ||
                                     profileContent.includes('State') ||
                                     profileContent.includes('Country');
            
            const hasCertificationData = profileContent.includes('Certification Type:') ||
                                       profileContent.includes('Date Certified:');
            
            const hasTrainingData = profileContent.includes('Training Audience') ||
                                  profileContent.includes('Business Type');
            
            const hasBusinessData = profileContent.includes('Company') ||
                                  profileContent.includes('Website') ||
                                  profileContent.includes('Phone');
            
            return {
                hasLocationSection,
                hasCertificationData,
                hasTrainingData,
                hasBusinessData,
                profileSections: Array.from(document.querySelectorAll('.hvac-profile-section h2')).map(h => h.textContent),
                profilePreview: profileContent.slice(0, 1000).replace(/\s+/g, ' ')
            };
        });
        
        console.log('📊 Profile data check:', profileCheck);
        
        // Now check the statistics to see if we have more location data
        console.log('\n📊 Getting updated geocoding statistics...');
        const updatedStats = await page.evaluate(async () => {
            try {
                const response = await fetch(hvac_ajax.ajax_url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'hvac_get_geocoding_stats',
                        nonce: hvac_ajax.nonce
                    })
                });
                
                const data = await response.json();
                return data;
            } catch (e) {
                return { error: 'Exception: ' + e.message };
            }
        });
        
        if (updatedStats.success) {
            const stats = updatedStats.data;
            console.log('📈 Updated Statistics:');
            console.log(`   Total Profiles: ${stats.total_profiles}`);
            console.log(`   Geocoded Profiles: ${stats.geocoded_profiles}`);
            console.log(`   Public Profiles: ${stats.public_profiles}`);
            console.log(`   Sync Issues: ${stats.sync_issues}`);
        }
        
        await page.screenshot({ path: 'csv-remigration-check.png', fullPage: true });
        
        console.log('\n================================================================================');
        console.log('🎯 CSV RE-MIGRATION TEST COMPLETE');
        
    } catch (error) {
        console.error('❌ Error during CSV re-migration test:', error);
        await page.screenshot({ path: 'csv-remigration-error.png', fullPage: true });
    } finally {
        await browser.close();
    }
}

testCsvRemigration();