const School = require('../models/School');

// Get all states
exports.getStates = async (req, res) => {
    try {
        console.log(`🏛️ [STATES DEBUG] Request received for all states`);
        console.log(`🏛️ [STATES DEBUG] Request URL: ${req.originalUrl}`);
        console.log(`🏛️ [STATES DEBUG] Request method: ${req.method}`);
        console.log(`🏛️ [STATES DEBUG] Request headers:`, req.headers);
        console.log(`🏛️ [STATES DEBUG] Request params:`, req.params);
        console.log(`🏛️ [STATES DEBUG] Request query:`, req.query);

        console.log(`🔍 [STATES DEBUG] Calling School.getStates()`);
        
        const states = await School.getStates();
        
        console.log(`📊 [STATES DEBUG] Query executed successfully`);
        console.log(`📊 [STATES DEBUG] Found ${states.length} states`);
        console.log(`📊 [STATES DEBUG] States data:`, JSON.stringify(states, null, 2));

        const responseData = {
            success: true,
            message: 'States retrieved successfully',
            data: {
                states,
                totalStates: states.length
            }
        };

        console.log(`✅ [STATES DEBUG] Sending response:`, JSON.stringify(responseData, null, 2));
        res.json(responseData);

    } catch (error) {
        console.error('❌ [STATES ERROR] Get states failed:', error);
        console.error('❌ [STATES ERROR] Error details:', {
            message: error.message,
            stack: error.stack,
            name: error.name,
            timestamp: new Date().toISOString()
        });
        
        res.status(500).json({
            success: false,
            message: 'Failed to retrieve states',
            error: error.message
        });
    }
};

// Get districts by state code
exports.getDistrictsByState = async (req, res) => {
    try {
        const { stateCode } = req.params;
        
        console.log(`🏛️ [DISTRICTS DEBUG] Request received for state code: ${stateCode}`);
        console.log(`🏛️ [DISTRICTS DEBUG] Request URL: ${req.originalUrl}`);
        console.log(`🏛️ [DISTRICTS DEBUG] Request method: ${req.method}`);
        console.log(`🏛️ [DISTRICTS DEBUG] Request headers:`, req.headers);
        console.log(`🏛️ [DISTRICTS DEBUG] Request params:`, req.params);
        console.log(`🏛️ [DISTRICTS DEBUG] Request query:`, req.query);

        if (!stateCode) {
            console.log(`❌ [DISTRICTS DEBUG] State code is missing`);
            return res.status(400).json({
                success: false,
                message: 'State code is required'
            });
        }

        console.log(`🔍 [DISTRICTS DEBUG] Searching for districts with state code: ${stateCode}`);
        console.log(`🔍 [DISTRICTS DEBUG] Calling School.getDistrictsByState(${stateCode})`);
        
        const districts = await School.getDistrictsByState(stateCode);
        
        console.log(`📊 [DISTRICTS DEBUG] Query executed successfully`);
        console.log(`📊 [DISTRICTS DEBUG] Found ${districts.length} districts`);
        console.log(`📊 [DISTRICTS DEBUG] Districts data:`, JSON.stringify(districts, null, 2));

        const responseData = {
            success: true,
            message: 'Districts retrieved successfully',
            data: {
                districts,
                totalDistricts: districts.length,
                stateCode
            }
        };

        console.log(`✅ [DISTRICTS DEBUG] Sending response:`, JSON.stringify(responseData, null, 2));
        res.json(responseData);

    } catch (error) {
        console.error('❌ [DISTRICTS ERROR] Get districts failed:', error);
        console.error('❌ [DISTRICTS ERROR] Error details:', {
            message: error.message,
            stack: error.stack,
            name: error.name,
            stateCode: req.params.stateCode,
            timestamp: new Date().toISOString()
        });
        
        res.status(500).json({
            success: false,
            message: 'Failed to retrieve districts',
            error: error.message
        });
    }
};

// Get villages by district code
exports.getVillagesByDistrict = async (req, res) => {
    try {
        const { districtCode } = req.params;
        
        console.log(`🏘️ [VILLAGES DEBUG] Request received for district code: ${districtCode}`);
        console.log(`🏘️ [VILLAGES DEBUG] Request URL: ${req.originalUrl}`);
        console.log(`🏘️ [VILLAGES DEBUG] Request method: ${req.method}`);
        console.log(`🏘️ [VILLAGES DEBUG] Request headers:`, req.headers);
        console.log(`🏘️ [VILLAGES DEBUG] Request params:`, req.params);
        console.log(`🏘️ [VILLAGES DEBUG] Request query:`, req.query);

        if (!districtCode) {
            console.log(`❌ [VILLAGES DEBUG] District code is missing`);
            return res.status(400).json({
                success: false,
                message: 'District code is required'
            });
        }

        console.log(`🔍 [VILLAGES DEBUG] Searching for villages with district code: ${districtCode}`);
        console.log(`🔍 [VILLAGES DEBUG] Calling School.getVillagesByDistrict(${districtCode})`);
        
        const villages = await School.getVillagesByDistrict(districtCode);
        
        console.log(`📊 [VILLAGES DEBUG] Query executed successfully`);
        console.log(`📊 [VILLAGES DEBUG] Found ${villages.length} villages`);
        console.log(`📊 [VILLAGES DEBUG] Villages data:`, JSON.stringify(villages, null, 2));

        const responseData = {
            success: true,
            message: 'Villages retrieved successfully',
            data: {
                villages,
                totalVillages: villages.length,
                districtCode
            }
        };

        console.log(`✅ [VILLAGES DEBUG] Sending response:`, JSON.stringify(responseData, null, 2));
        res.json(responseData);

    } catch (error) {
        console.error('❌ [VILLAGES ERROR] Get villages failed:', error);
        console.error('❌ [VILLAGES ERROR] Error details:', {
            message: error.message,
            stack: error.stack,
            name: error.name,
            districtCode: req.params.districtCode,
            timestamp: new Date().toISOString()
        });
        
        res.status(500).json({
            success: false,
            message: 'Failed to retrieve villages',
            error: error.message
        });
    }
};

// Get schools by village code
exports.getSchoolsByVillage = async (req, res) => {
    try {
        console.log(`🏫 [SCHOOLS DEBUG] Request received for village code: ${req.params.villageCode}`);
        console.log(`🏫 [SCHOOLS DEBUG] Request URL: ${req.url}`);
        console.log(`🏫 [SCHOOLS DEBUG] Request method: ${req.method}`);
        console.log(`🏫 [SCHOOLS DEBUG] Request headers:`, req.headers);
        console.log(`🏫 [SCHOOLS DEBUG] Request params:`, req.params);
        console.log(`🏫 [SCHOOLS DEBUG] Request query:`, req.query);
        
        const { villageCode } = req.params;

        if (!villageCode) {
            console.log(`❌ [SCHOOLS DEBUG] No village code provided`);
            return res.status(400).json({
                success: false,
                message: 'Village code is required'
            });
        }

        console.log(`🔍 [SCHOOLS DEBUG] Searching for schools with village code: ${villageCode}`);
        console.log(`🔍 [SCHOOLS DEBUG] Calling School.getSchoolsByVillage(${villageCode})`);
        
        const schools = await School.getSchoolsByVillage(villageCode);
        
        console.log(`📊 [SCHOOLS DEBUG] Query executed successfully`);
        console.log(`📊 [SCHOOLS DEBUG] Found ${schools.length} schools`);
        console.log(`📊 [SCHOOLS DEBUG] Schools data:`, JSON.stringify(schools, null, 2));

        // Format response to show only school_name and udise_school_code
        const formattedSchools = schools.map(school => ({
            school_name: school.school_name,
            udise_school_code: school.udise_school_code
        }));

        res.json({
            success: true,
            message: 'Schools retrieved successfully',
            data: {
                schools: formattedSchools,
                totalSchools: schools.length,
                villageCode
            }
        });

    } catch (error) {
        console.error('❌ [SCHOOLS ERROR] Get schools failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to retrieve schools',
            error: error.message
        });
    }
};

// Search schools by name
exports.searchSchoolsByName = async (req, res) => {
    try {
        const { schoolName, limit = 10 } = req.query;

        if (!schoolName) {
            return res.status(400).json({
            success: false,
                message: 'School name is required'
            });
        }

        const schools = await School.searchSchoolsByName(schoolName, limit);

        res.json({
            success: true,
            message: 'Schools found successfully',
            data: {
                schools,
                totalSchools: schools.length,
                searchQuery: schoolName
            }
        });

    } catch (error) {
        console.error('Search schools error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to search schools',
            error: error.message
        });
    }
};

// Get school by UDISE code
exports.getSchoolByUdiseCode = async (req, res) => {
    try {
        const { udiseCode } = req.params;

        if (!udiseCode) {
            return res.status(400).json({
                success: false,
                message: 'UDISE code is required'
            });
        }

        const school = await School.getSchoolByUdiseCode(udiseCode);
        
        if (!school) {
            return res.status(404).json({
                success: false,
                message: 'School not found',
                data: null
            });
        }

        res.json({
            success: true,
            message: 'School retrieved successfully',
            data: {
                school
            }
        });

    } catch (error) {
        console.error('Get school error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to retrieve school',
            error: error.message
        });
    }
};