const mongoose = require('mongoose');

const collegeSchema = new mongoose.Schema({
    // Map to actual database field names (with underscores)
    AISHE_Code: {
        type: String,
        required: [true, 'AISHE Code is required'],
        unique: true,
        trim: true,
        maxlength: [20, 'AISHE Code cannot exceed 20 characters'],
        index: true
    },
    
    Institute_Name: {
        type: String,
        required: [true, 'Institute name is required'],
        trim: true,
        maxlength: [500, 'Institute name cannot exceed 500 characters'],
        index: true
    },
    
    City: {
        type: String,
        required: [true, 'City is required'],
        trim: true,
        maxlength: [100, 'City name cannot exceed 100 characters'],
        index: true
    },
    
    State: {
            type: String,
        required: [true, 'State is required'],
        trim: true,
        maxlength: [100, 'State name cannot exceed 100 characters'],
        index: true
    }
}, {
    timestamps: true,
    collection: 'colleges'
});

// Index for text search on institute name
collegeSchema.index({ Institute_Name: 'text' });

// Static method to search colleges by name
collegeSchema.statics.searchCollegesByName = async function(searchTerm, limit = 20) {
    console.log(`🔍 [COLLEGE SEARCH DEBUG] Searching colleges with term: ${searchTerm}`);
    console.log(`🔍 [COLLEGE SEARCH DEBUG] Limit: ${limit}`);
    
    try {
        const colleges = await this.find({
            $or: [
                { Institute_Name: { $regex: searchTerm, $options: 'i' } },
                { City: { $regex: searchTerm, $options: 'i' } },
                { State: { $regex: searchTerm, $options: 'i' } },
                { AISHE_Code: { $regex: searchTerm, $options: 'i' } }
            ]
        })
        .select('AISHE_Code Institute_Name City State')
        .sort({ Institute_Name: 1 })
        .limit(parseInt(limit));
        
        console.log(`📊 [COLLEGE SEARCH DEBUG] Found ${colleges.length} colleges`);
        return colleges;
        
    } catch (error) {
        console.error(`❌ [COLLEGE SEARCH ERROR] Search failed:`, error);
        throw error;
    }
};

// Static method to get colleges by state
collegeSchema.statics.getCollegesByState = async function(stateName) {
    console.log(`🏛️ [COLLEGE STATE DEBUG] Getting colleges for state: ${stateName}`);
    
    try {
        const colleges = await this.find({ State: stateName })
            .select('AISHE_Code Institute_Name City State')
            .sort({ Institute_Name: 1 });
        
        console.log(`📊 [COLLEGE STATE DEBUG] Found ${colleges.length} colleges in ${stateName}`);
        return colleges;
        
    } catch (error) {
        console.error(`❌ [COLLEGE STATE ERROR] Get colleges by state failed:`, error);
        throw error;
    }
};

// Static method to get colleges by city
collegeSchema.statics.getCollegesByCity = async function(cityName) {
    console.log(`🏙️ [COLLEGE CITY DEBUG] Getting colleges for city: ${cityName}`);
    
    try {
        const colleges = await this.find({ City: cityName })
            .select('AISHE_Code Institute_Name City State')
            .sort({ Institute_Name: 1 });
        
        console.log(`📊 [COLLEGE CITY DEBUG] Found ${colleges.length} colleges in ${cityName}`);
        return colleges;
        
    } catch (error) {
        console.error(`❌ [COLLEGE CITY ERROR] Get colleges by city failed:`, error);
        throw error;
    }
};

// Static method to get all states
collegeSchema.statics.getStates = async function() {
    console.log(`🗺️ [COLLEGE STATES DEBUG] Getting all states`);
    
    try {
        const states = await this.distinct('State');
        console.log(`📊 [COLLEGE STATES DEBUG] Found ${states.length} states`);
        return states.sort();
        
    } catch (error) {
        console.error(`❌ [COLLEGE STATES ERROR] Get states failed:`, error);
        throw error;
    }
};

// Static method to get all cities
collegeSchema.statics.getCities = async function() {
    console.log(`🏙️ [COLLEGE CITIES DEBUG] Getting all cities`);
    
    try {
        const cities = await this.distinct('City');
        console.log(`📊 [COLLEGE CITIES DEBUG] Found ${cities.length} cities`);
        return cities.sort();
        
    } catch (error) {
        console.error(`❌ [COLLEGE CITIES ERROR] Get cities failed:`, error);
        throw error;
    }
};

// Static method to get college by AISHE code
collegeSchema.statics.getCollegeByAisheCode = async function(aisheCode) {
    console.log(`🎓 [COLLEGE AISHE DEBUG] Getting college by AISHE code: ${aisheCode}`);
    
    try {
        const college = await this.findOne({ AISHE_Code: aisheCode })
            .select('AISHE_Code Institute_Name City State');
        
        if (college) {
            console.log(`✅ [COLLEGE AISHE DEBUG] College found: ${college.Institute_Name}`);
        } else {
            console.log(`❌ [COLLEGE AISHE DEBUG] College not found for AISHE code: ${aisheCode}`);
        }
        
        return college;
        
    } catch (error) {
        console.error(`❌ [COLLEGE AISHE ERROR] Get college by AISHE code failed:`, error);
        throw error;
    }
};

module.exports = mongoose.model('College', collegeSchema, 'colleges');