const CareerGoal = require('../models/CareerGoal');
const CareerPath = require('../models/CareerPath');
const CareerProgress = require('../models/CareerProgress');
const User = require('../models/User');

// Set career goal
const setCareerGoal = async (req, res) => {
    try {
        const { selectedPath, currentStage, specificGoal, targetYear } = req.body;
        const userId = req.user.id;

        // Check if user already has a career goal
        const existingGoal = await CareerGoal.findOne({ userId });
        
        if (existingGoal) {
            existingGoal.selectedPath = selectedPath;
            existingGoal.currentStage = currentStage;
            existingGoal.specificGoal = specificGoal;
            existingGoal.targetYear = targetYear;
            existingGoal.progressPercentage = 0;
            await existingGoal.save();
            
            return res.status(200).json({
                success: true,
                message: 'Career goal updated successfully',
                data: existingGoal
            });
        }

        const careerGoal = new CareerGoal({
            userId,
            selectedPath,
            currentStage,
            specificGoal,
            targetYear
        });

        await careerGoal.save();

        // Update user's occupation based on stage
        await User.findByIdAndUpdate(userId, {
            occupation: currentStage === 'working_professional' ? 'working professional' : 'school student'
        });

        res.status(201).json({
            success: true,
            message: 'Career goal set successfully',
            data: careerGoal
        });
    } catch (error) {
        console.error('Set career goal error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to set career goal',
            error: error.message
        });
    }
};

// Get career paths for a specific stage
const getCareerPaths = async (req, res) => {
    try {
        const { stage } = req.params;

        const careerPaths = await CareerPath.find({ 
            stage,
            isActive: true 
        }).select('-__v');

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

// Get user's career goal
const getCareerGoal = async (req, res) => {
    try {
        const userId = req.user.id;

        const careerGoal = await CareerGoal.findOne({ userId }).populate('userId', 'name mobile');

        if (!careerGoal) {
            return res.status(404).json({
                success: false,
                message: 'No career goal found'
            });
        }

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

// Update career goal progress
const updateCareerProgress = async (req, res) => {
    try {
        const { progressPercentage, isCompleted } = req.body;
        const userId = req.user.id;

        const careerGoal = await CareerGoal.findOne({ userId });

        if (!careerGoal) {
            return res.status(404).json({
                success: false,
                message: 'No career goal found'
            });
        }

        careerGoal.progressPercentage = progressPercentage || careerGoal.progressPercentage;
        careerGoal.isCompleted = isCompleted !== undefined ? isCompleted : careerGoal.isCompleted;

        await careerGoal.save();

        // Update career progress
        let careerProgress = await CareerProgress.findOne({ userId });
        if (!careerProgress) {
            careerProgress = new CareerProgress({ userId, currentStage: careerGoal.currentStage });
        }

        // Update goal progress in career progress
        const goalIndex = careerProgress.goals.findIndex(goal => 
            goal.goalId.toString() === careerGoal._id.toString()
        );

        if (goalIndex !== -1) {
            careerProgress.goals[goalIndex].progress = progressPercentage || 0;
        } else {
            careerProgress.goals.push({
                goalId: careerGoal._id,
                progress: progressPercentage || 0,
                milestones: []
            });
        }

        await careerProgress.save();

        res.status(200).json({
            success: true,
            message: 'Career progress updated successfully',
            data: {
                careerGoal,
                careerProgress
            }
        });
    } catch (error) {
        console.error('Update career progress error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update career progress',
            error: error.message
        });
    }
};

// Get career suggestions based on user's goal
const getCareerSuggestions = async (req, res) => {
    try {
        const userId = req.user.id;

        const careerGoal = await CareerGoal.findOne({ userId });
        if (!careerGoal) {
            return res.status(404).json({
                success: false,
                message: 'No career goal found'
            });
        }

        // Get related career paths
        const relatedPaths = await CareerPath.find({
            stage: careerGoal.currentStage,
            isActive: true
        });

        // Get suggested exams, colleges, certifications based on selected path
        const suggestions = {
            careerPath: relatedPaths.find(path => 
                path.name.toLowerCase().includes(careerGoal.selectedPath.toLowerCase())
            ),
            nextSteps: [],
            recommendations: []
        };

        // Add basic recommendations based on stage
        if (careerGoal.currentStage === 'class_11_12') {
            suggestions.recommendations.push(
                'Focus on entrance exam preparation',
                'Join study groups for peer learning',
                'Take regular mock tests',
                'Maintain good academic performance'
            );
        } else if (careerGoal.currentStage === 'graduation') {
            suggestions.recommendations.push(
                'Consider higher studies options',
                'Build relevant skills for your field',
                'Look for internship opportunities',
                'Network with professionals in your field'
            );
        }

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

// Get user's career progress
const getCareerProgress = async (req, res) => {
    try {
        const userId = req.user.id;

        let careerProgress = await CareerProgress.findOne({ userId })
            .populate('goals.goalId', 'selectedPath specificGoal progressPercentage');

        if (!careerProgress) {
            // Create initial progress record
            careerProgress = new CareerProgress({
                userId,
                currentStage: 'class_6_10'
            });
            await careerProgress.save();
        }

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

module.exports = {
    setCareerGoal,
    getCareerPaths,
    getCareerGoal,
    updateCareerProgress,
    getCareerSuggestions,
    getCareerProgress
};
