const axios = require('axios');

const BASE_URL = 'http://localhost:5500';

async function testSchoolsAPI() {
    console.log('🧪 [TEST] Testing Schools API...\n');
    
    // Test cases with different village codes
    const testCases = [
        {
            name: 'Test with sample village code',
            villageCode: '350103001',
            expected: 'success'
        },
        {
            name: 'Test with numeric village code',
            villageCode: '350103001',
            expected: 'success'
        },
        {
            name: 'Test with string village code',
            villageCode: '350103001',
            expected: 'success'
        },
        {
            name: 'Test with invalid village code',
            villageCode: 'invalid_code',
            expected: 'success' // Should return empty array, not error
        }
    ];
    
    for (const testCase of testCases) {
        try {
            console.log(`📝 [TEST] ${testCase.name}...`);
            console.log(`📝 [TEST] Village Code: ${testCase.villageCode}`);
            
            const response = await axios.get(`${BASE_URL}/api/schools/schools/${testCase.villageCode}`);
            
            console.log(`✅ [TEST] ${testCase.name} - SUCCESS`);
            console.log(`✅ [TEST] Response:`, JSON.stringify(response.data, null, 2));
            
            // Check if we got schools
            if (response.data.success && response.data.data.totalSchools > 0) {
                console.log(`🎉 [TEST] Found ${response.data.data.totalSchools} schools!`);
                response.data.data.schools.forEach((school, index) => {
                    console.log(`  ${index + 1}. ${school.school_name} (${school.udise_school_code})`);
                });
            } else {
                console.log(`⚠️ [TEST] No schools found for village code: ${testCase.villageCode}`);
            }
            
        } catch (error) {
            console.log(`❌ [TEST] ${testCase.name} - ERROR`);
            console.log(`❌ [TEST] Error:`, error.response?.data || error.message);
        }
        
        console.log('---\n');
    }
    
    // Test the complete workflow
    console.log('🔄 [TEST] Testing complete workflow...\n');
    
    try {
        // Step 1: Get states
        console.log('📝 [TEST] Step 1: Getting states...');
        const statesResponse = await axios.get(`${BASE_URL}/api/schools/states`);
        console.log(`✅ [TEST] Found ${statesResponse.data.data.totalStates} states`);
        
        if (statesResponse.data.data.states.length > 0) {
            const firstState = statesResponse.data.data.states[0];
            console.log(`📝 [TEST] Using first state: ${firstState.state_name} (${firstState.state_code})`);
            
            // Step 2: Get districts for first state
            console.log('📝 [TEST] Step 2: Getting districts...');
            const districtsResponse = await axios.get(`${BASE_URL}/api/schools/districts/${firstState.state_code}`);
            console.log(`✅ [TEST] Found ${districtsResponse.data.data.totalDistricts} districts`);
            
            if (districtsResponse.data.data.districts.length > 0) {
                const firstDistrict = districtsResponse.data.data.districts[0];
                console.log(`📝 [TEST] Using first district: ${firstDistrict.district_name} (${firstDistrict.district_code})`);
                
                // Step 3: Get villages for first district
                console.log('📝 [TEST] Step 3: Getting villages...');
                const villagesResponse = await axios.get(`${BASE_URL}/api/schools/villages/${firstDistrict.district_code}`);
                console.log(`✅ [TEST] Found ${villagesResponse.data.data.totalVillages} villages`);
                
                if (villagesResponse.data.data.villages.length > 0) {
                    const firstVillage = villagesResponse.data.data.villages[0];
                    console.log(`📝 [TEST] Using first village: ${firstVillage.village_name} (${firstVillage.udise_village_code})`);
                    
                    // Step 4: Get schools for first village
                    console.log('📝 [TEST] Step 4: Getting schools...');
                    const schoolsResponse = await axios.get(`${BASE_URL}/api/schools/schools/${firstVillage.udise_village_code}`);
                    console.log(`✅ [TEST] Found ${schoolsResponse.data.data.totalSchools} schools`);
                    
                    if (schoolsResponse.data.data.schools.length > 0) {
                        console.log(`🎉 [TEST] SUCCESS! Found schools:`);
                        schoolsResponse.data.data.schools.forEach((school, index) => {
                            console.log(`  ${index + 1}. ${school.school_name} (${school.udise_school_code})`);
                        });
                    } else {
                        console.log(`⚠️ [TEST] No schools found for village: ${firstVillage.village_name}`);
                    }
                } else {
                    console.log(`⚠️ [TEST] No villages found for district: ${firstDistrict.district_name}`);
                }
            } else {
                console.log(`⚠️ [TEST] No districts found for state: ${firstState.state_name}`);
            }
        } else {
            console.log(`⚠️ [TEST] No states found`);
        }
        
    } catch (error) {
        console.error('❌ [TEST] Workflow test failed:', error.response?.data || error.message);
    }
    
    console.log('\n🎉 [TEST] Schools API tests completed!');
}

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