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

// Search colleges by name
exports.searchCollegesByName = async (req, res) => {
    try {
        const { name, limit = 20 } = req.query;
        
        console.log(`🔍 [COLLEGE SEARCH DEBUG] Search request received`);
        console.log(`🔍 [COLLEGE SEARCH DEBUG] Search term: ${name}`);
        console.log(`🔍 [COLLEGE SEARCH DEBUG] Limit: ${limit}`);
        
        if (!name || name.trim() === '') {
            return res.status(400).json({
                success: false,
                message: 'Search term is required'
            });
        }
        
        const colleges = await College.searchCollegesByName(name, limit);
        
        console.log(`📊 [COLLEGE SEARCH DEBUG] Found ${colleges.length} colleges`);
        
        res.json({
            success: true,
            message: 'Colleges retrieved successfully',
            data: {
                colleges,
                totalColleges: colleges.length,
                searchTerm: name,
                limit: parseInt(limit)
            }
        });
        
    } catch (error) {
        console.error('❌ [COLLEGE SEARCH ERROR] Search colleges failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to search colleges',
            error: error.message
        });
    }
};

// Get colleges by state
exports.getCollegesByState = async (req, res) => {
    try {
        const { stateName } = req.params;
        
        console.log(`🏛️ [COLLEGE STATE DEBUG] Get colleges by state request received`);
        console.log(`🏛️ [COLLEGE STATE DEBUG] State: ${stateName}`);

        if (!stateName || stateName.trim() === '') {
            return res.status(400).json({
                success: false,
                message: 'State name is required'
            });
        }
        
        const colleges = await College.getCollegesByState(stateName);
        
        console.log(`📊 [COLLEGE STATE DEBUG] Found ${colleges.length} colleges in ${stateName}`);
        
        res.json({
            success: true,
            message: 'Colleges retrieved successfully',
            data: {
                colleges,
                totalColleges: colleges.length,
                stateName
            }
        });
        
    } catch (error) {
        console.error('❌ [COLLEGE STATE ERROR] Get colleges by state failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get colleges by state',
            error: error.message
        });
    }
};

// Get colleges by city
exports.getCollegesByCity = async (req, res) => {
    try {
        const { cityName } = req.params;

        console.log(`🏙️ [COLLEGE CITY DEBUG] Get colleges by city request received`);
        console.log(`🏙️ [COLLEGE CITY DEBUG] City: ${cityName}`);

        if (!cityName || cityName.trim() === '') {
            return res.status(400).json({
                success: false,
                message: 'City name is required'
            });
        }
        
        const colleges = await College.getCollegesByCity(cityName);
        
        console.log(`📊 [COLLEGE CITY DEBUG] Found ${colleges.length} colleges in ${cityName}`);
        
        res.json({
            success: true,
            message: 'Colleges retrieved successfully',
            data: {
                colleges,
                totalColleges: colleges.length,
                cityName
            }
        });
        
    } catch (error) {
        console.error('❌ [COLLEGE CITY ERROR] Get colleges by city failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get colleges by city',
            error: error.message
        });
    }
};

// Get all states
exports.getStates = async (req, res) => {
    try {
        console.log(`🗺️ [COLLEGE STATES DEBUG] Get all states request received`);
        
        const states = await College.getStates();
        
        console.log(`📊 [COLLEGE STATES DEBUG] Found ${states.length} states`);
        
        res.json({
            success: true,
            message: 'States retrieved successfully',
            data: {
                states,
                totalStates: states.length
            }
        });
        
    } catch (error) {
        console.error('❌ [COLLEGE STATES ERROR] Get states failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get states',
            error: error.message
        });
    }
};

// Get all cities
exports.getCities = async (req, res) => {
    try {
        console.log(`🏙️ [COLLEGE CITIES DEBUG] Get all cities request received`);

        const cities = await College.getCities();

        console.log(`📊 [COLLEGE CITIES DEBUG] Found ${cities.length} cities`);

        res.json({
            success: true,
            message: 'Cities retrieved successfully',
            data: {
                cities,
                totalCities: cities.length
            }
        });
        
    } catch (error) {
        console.error('❌ [COLLEGE CITIES ERROR] Get cities failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get cities',
            error: error.message
        });
    }
};

// Get all colleges (for dropdown)
exports.getAllColleges = async (req, res) => {
    try {
        const { search = '' } = req.query;
        
        console.log(`📋 [COLLEGE ALL DEBUG] ==========================================`);
        console.log(`📋 [COLLEGE ALL DEBUG] Get all colleges request received`);
        console.log(`📋 [COLLEGE ALL DEBUG] Request URL: ${req.originalUrl}`);
        console.log(`📋 [COLLEGE ALL DEBUG] Request method: ${req.method}`);
        console.log(`📋 [COLLEGE ALL DEBUG] Request headers:`, req.headers);
        console.log(`📋 [COLLEGE ALL DEBUG] Request query:`, req.query);
        console.log(`📋 [COLLEGE ALL DEBUG] Search term: "${search}"`);
        console.log(`📋 [COLLEGE ALL DEBUG] Search term type: ${typeof search}`);
        console.log(`📋 [COLLEGE ALL DEBUG] Search term length: ${search.length}`);
        
        // Build search query
        let query = {};
        if (search && search.trim() !== '') {
            console.log(`🔍 [COLLEGE ALL DEBUG] Building search query for: "${search}"`);
            query = {
                $or: [
                    { Institute_Name: { $regex: search, $options: 'i' } },
                    { City: { $regex: search, $options: 'i' } },
                    { State: { $regex: search, $options: 'i' } },
                    { AISHE_Code: { $regex: search, $options: 'i' } }
                ]
            };
            console.log(`🔍 [COLLEGE ALL DEBUG] Search query:`, JSON.stringify(query, null, 2));
        } else {
            console.log(`🔍 [COLLEGE ALL DEBUG] No search term provided, getting all colleges`);
        }
        
        console.log(`📊 [COLLEGE ALL DEBUG] Executing database query...`);
        const startTime = Date.now();
        
        const colleges = await College.find(query)
            .select('AISHE_Code Institute_Name City State')
            .sort({ Institute_Name: 1 });
        
        const endTime = Date.now();
        const queryTime = endTime - startTime;
        
        console.log(`📊 [COLLEGE ALL DEBUG] Database query completed in ${queryTime}ms`);
        console.log(`📊 [COLLEGE ALL DEBUG] Found ${colleges.length} colleges`);
        
        if (colleges.length > 0) {
            console.log(`📊 [COLLEGE ALL DEBUG] First college:`, {
                aisheCode: colleges[0].AISHE_Code,
                instituteName: colleges[0].Institute_Name,
                city: colleges[0].City,
                state: colleges[0].State
            });
            
            if (colleges.length > 1) {
                console.log(`📊 [COLLEGE ALL DEBUG] Last college:`, {
                    aisheCode: colleges[colleges.length - 1].AISHE_Code,
                    instituteName: colleges[colleges.length - 1].Institute_Name,
                    city: colleges[colleges.length - 1].City,
                    state: colleges[colleges.length - 1].State
                });
            }
        }
        
        // Map database field names to API field names
        const mappedColleges = colleges.map(college => ({
            aisheCode: college.AISHE_Code,
            instituteName: college.Institute_Name,
            city: college.City,
            state: college.State
        }));

        const responseData = {
            success: true,
            message: 'Colleges retrieved successfully',
            data: {
                colleges: mappedColleges,
                totalColleges: colleges.length,
                searchTerm: search
            }
        };
        
        console.log(`✅ [COLLEGE ALL DEBUG] Response data:`, {
            success: responseData.success,
            message: responseData.message,
            totalColleges: responseData.data.totalColleges,
            searchTerm: responseData.data.searchTerm
        });
        
        console.log(`📋 [COLLEGE ALL DEBUG] ==========================================`);
        
        res.json(responseData);
        
    } catch (error) {
        console.error(`❌ [COLLEGE ALL ERROR] ==========================================`);
        console.error(`❌ [COLLEGE ALL ERROR] Get all colleges failed:`, error);
        console.error(`❌ [COLLEGE ALL ERROR] Error message:`, error.message);
        console.error(`❌ [COLLEGE ALL ERROR] Error stack:`, error.stack);
        console.error(`❌ [COLLEGE ALL ERROR] Request details:`, {
            url: req.originalUrl,
            method: req.method,
            query: req.query,
            headers: req.headers
        });
        console.error(`❌ [COLLEGE ALL ERROR] ==========================================`);
        
        res.status(500).json({
            success: false,
            message: 'Failed to get colleges',
            error: error.message
        });
    }
};

// Get college by AISHE code
exports.getCollegeByAisheCode = async (req, res) => {
    try {
        const { aisheCode } = req.params;
        
        console.log(`🎓 [COLLEGE AISHE DEBUG] Get college by AISHE code request received`);
        console.log(`🎓 [COLLEGE AISHE DEBUG] AISHE Code: ${aisheCode}`);
        
        if (!aisheCode || aisheCode.trim() === '') {
            return res.status(400).json({
                success: false,
                message: 'AISHE code is required'
            });
        }
        
        const college = await College.getCollegeByAisheCode(aisheCode);
        
        if (!college) {
            return res.status(404).json({
                success: false,
                message: 'College not found'
            });
        }
        
        console.log(`✅ [COLLEGE AISHE DEBUG] College found: ${college.instituteName}`);
        
        res.json({
            success: true,
            message: 'College retrieved successfully',
            data: {
                college
            }
        });
        
    } catch (error) {
        console.error('❌ [COLLEGE AISHE ERROR] Get college by AISHE code failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get college',
            error: error.message
        });
    }
};