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

async function testTrainerApprovalWorkflow() {
    console.log('🧪 Testing Trainer Approval Workflow...\n');
    
    const browser = await chromium.launch({ headless: false });
    const context = await browser.newContext();
    const page = await context.newPage();
    
    // Ensure screenshots directory exists
    const screenshotDir = path.join(__dirname, 'test-screenshots');
    if (!fs.existsSync(screenshotDir)) {
        fs.mkdirSync(screenshotDir, { recursive: true });
    }
    
    try {
        // Test 1: Check Registration Page
        console.log('1️⃣ Testing Registration Page...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/registration/');
        await page.waitForLoadState('networkidle');
        
        // Take screenshot of registration page
        await page.screenshot({ 
            path: path.join(screenshotDir, '01-registration-page.png'),
            fullPage: true 
        });
        
        // Check if form exists
        const formExists = await page.locator('#hvac-registration-form').count() > 0;
        console.log(`  ✅ Registration form exists: ${formExists}`);
        
        // Check for required fields
        const requiredFields = [
            '#user_email', '#user_pass', '#confirm_password',
            '#first_name', '#last_name', '#display_name',
            '#business_name', '#business_phone', '#business_email'
        ];
        
        console.log('  📋 Checking required fields...');
        for (const field of requiredFields) {
            const exists = await page.locator(field).count() > 0;
            console.log(`    ${exists ? '✅' : '❌'} ${field}`);
        }
        
        // Test 2: Check Pending Page
        console.log('\n2️⃣ Testing Pending Status Page...');
        await page.goto('https://upskill-staging.measurequick.com/trainer-account-pending/');
        await page.waitForLoadState('networkidle');
        
        await page.screenshot({ 
            path: path.join(screenshotDir, '02-pending-page.png'),
            fullPage: true 
        });
        
        const pendingH1 = await page.locator('h1').textContent();
        console.log(`  📄 Pending page title: "${pendingH1}"`);
        
        // Test 3: Check Disabled Page
        console.log('\n3️⃣ Testing Disabled Status Page...');
        await page.goto('https://upskill-staging.measurequick.com/trainer-account-disabled/');
        await page.waitForLoadState('networkidle');
        
        await page.screenshot({ 
            path: path.join(screenshotDir, '03-disabled-page.png'),
            fullPage: true 
        });
        
        const disabledH1 = await page.locator('h1').textContent();
        console.log(`  📄 Disabled page title: "${disabledH1}"`);
        
        // Test 4: Check Master Dashboard (login required)
        console.log('\n4️⃣ Testing Master Dashboard Login...');
        
        // Login 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');
        
        // Wait for login to complete
        await page.waitForURL(/wp-admin|master-trainer/, { timeout: 30000 });
        
        // Navigate to master dashboard
        await page.goto('https://upskill-staging.measurequick.com/master-trainer/dashboard/');
        await page.waitForLoadState('networkidle');
        
        await page.screenshot({ 
            path: path.join(screenshotDir, '04-master-dashboard.png'),
            fullPage: true 
        });
        
        // Check for trainer table
        const hasTrainerTable = await page.locator('.trainers-table-container').count() > 0;
        console.log(`  ✅ Master dashboard trainer table exists: ${hasTrainerTable}`);
        
        // Check for filter controls
        const hasStatusFilter = await page.locator('#trainer-status-filter').count() > 0;
        const hasSearchBox = await page.locator('#trainer-search').count() > 0;
        const hasBulkUpdate = await page.locator('#bulk-status-update').count() > 0;
        
        console.log(`  ✅ Status filter exists: ${hasStatusFilter}`);
        console.log(`  ✅ Search box exists: ${hasSearchBox}`);
        console.log(`  ✅ Bulk update dropdown exists: ${hasBulkUpdate}`);
        
        // Try filtering by pending
        if (hasStatusFilter) {
            await page.selectOption('#trainer-status-filter', 'pending');
            await page.click('#apply-trainer-filters');
            await page.waitForTimeout(2000);
            
            await page.screenshot({ 
                path: path.join(screenshotDir, '05-master-dashboard-pending.png'),
                fullPage: true 
            });
            
            const hasPendingTrainers = await page.locator('.trainers-table tr').count() > 1 || 
                                       await page.locator('.no-data-message').count() > 0;
            console.log(`  ✅ Pending filter works: ${hasPendingTrainers}`);
        }
        
        // Test 5: Registration Success Page
        console.log('\n5️⃣ Testing Registration Success Page...');
        await page.goto('https://upskill-staging.measurequick.com/registration-pending/');
        await page.waitForLoadState('networkidle');
        
        await page.screenshot({ 
            path: path.join(screenshotDir, '06-registration-success.png'),
            fullPage: true 
        });
        
        const successH1 = await page.locator('h1').textContent();
        console.log(`  📄 Success page title: "${successH1}"`);
        
        console.log('\n✅ All tests completed!');
        console.log(`\n📸 Screenshots saved to: ${screenshotDir}`);
        
    } catch (error) {
        console.error('❌ Test failed:', error);
        await page.screenshot({ 
            path: path.join(screenshotDir, 'error-screenshot.png'),
            fullPage: true 
        });
    } finally {
        await browser.close();
    }
}

// Run the test
testTrainerApprovalWorkflow().catch(console.error);