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

// Check college eligibility based on rank
const checkCollegeEligibility = async (req, res) => {
    try {
        const { rank, category, exam, specialization } = req.query;
        
        if (!rank || !category || !exam) {
            return res.status(400).json({
                success: false,
                message: 'Rank, category, and exam are required'
            });
        }

        const userRank = parseInt(rank);
        const filter = { exam, isActive: true };
        if (specialization) filter.course = new RegExp(specialization, 'i');

        const colleges = await CollegeEligibility.find(filter);

        const eligibleColleges = colleges.map(college => {
            const cutoff = college.cutoffs[category] || college.cutoffs.general;
            let eligibility = 'Not Eligible';
            let probability = 'Low';
            
            if (userRank <= college.rankRanges.safe.max) {
                eligibility = 'Eligible';
                probability = 'Very High';
            } else if (userRank <= college.rankRanges.moderate.max) {
                eligibility = 'Eligible';
                probability = 'High';
            } else if (userRank <= college.rankRanges.risky.max) {
                eligibility = 'Eligible';
                probability = 'Moderate';
            }

            return {
                ...college.toObject(),
                userRank,
                eligibility,
                probability,
                cutoffRank: cutoff
            };
        }).filter(college => college.eligibility === 'Eligible');

        // Sort by probability and ranking
        eligibleColleges.sort((a, b) => {
            if (a.probability !== b.probability) {
                const probOrder = { 'Very High': 4, 'High': 3, 'Moderate': 2, 'Low': 1 };
                return probOrder[b.probability] - probOrder[a.probability];
            }
            return a.ranking.nirf - b.ranking.nirf;
        });

        // Generate recommendations
        const recommendations = generateRecommendations(eligibleColleges, userRank);

        res.status(200).json({
            success: true,
            data: {
                userRank: parseInt(rank),
                exam,
                category,
                specialization,
                eligibleColleges,
                recommendations,
                totalEligible: eligibleColleges.length
            }
        });
    } catch (error) {
        console.error('Check college eligibility error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to check college eligibility',
            error: error.message
        });
    }
};

// Generate recommendations based on eligible colleges
const generateRecommendations = (colleges, userRank) => {
    const recommendations = [];
    
    if (colleges.length === 0) {
        recommendations.push('Consider improving your rank for better options');
        return recommendations;
    }

    const topColleges = colleges.filter(c => c.probability === 'Very High' || c.probability === 'High');
    const moderateColleges = colleges.filter(c => c.probability === 'Moderate');

    if (topColleges.length > 0) {
        recommendations.push(`${topColleges[0].collegeName} is your best option`);
    }

    if (moderateColleges.length > 0) {
        recommendations.push(`Consider ${moderateColleges[0].collegeName} as a backup option`);
    }

    if (colleges.length > 3) {
        recommendations.push('You have multiple good options to choose from');
    }

    return recommendations;
};

// Get cutoff data for a specific exam
const getCutoffData = async (req, res) => {
    try {
        const { exam } = req.params;
        
        const colleges = await CollegeEligibility.find({ 
            exam, 
            isActive: true 
        }).select('collegeName course cutoffs ranking');

        res.status(200).json({
            success: true,
            data: colleges
        });
    } catch (error) {
        console.error('Get cutoff data error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get cutoff data',
            error: error.message
        });
    }
};

// Create college eligibility (Admin only)
const createCollegeEligibility = async (req, res) => {
    try {
        const eligibilityData = req.body;
        
        const eligibility = new CollegeEligibility(eligibilityData);
        await eligibility.save();

        res.status(201).json({
            success: true,
            message: 'College eligibility created successfully',
            data: eligibility
        });
    } catch (error) {
        console.error('Create college eligibility error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to create college eligibility',
            error: error.message
        });
    }
};

// Update college eligibility (Admin only)
const updateCollegeEligibility = async (req, res) => {
    try {
        const { eligibilityId } = req.params;
        const updateData = req.body;

        const eligibility = await CollegeEligibility.findByIdAndUpdate(
            eligibilityId,
            updateData,
            { new: true, runValidators: true }
        );

        if (!eligibility) {
            return res.status(404).json({
                success: false,
                message: 'College eligibility not found'
            });
        }

        res.status(200).json({
            success: true,
            message: 'College eligibility updated successfully',
            data: eligibility
        });
    } catch (error) {
        console.error('Update college eligibility error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update college eligibility',
            error: error.message
        });
    }
};

module.exports = {
    checkCollegeEligibility,
    getCutoffData,
    createCollegeEligibility,
    updateCollegeEligibility
};
