const PortfolioAnalysis = require('../models/PortfolioAnalysis');
const User = require('../models/User');

// Get portfolio analysis for user
const getPortfolioAnalysis = async (req, res) => {
    try {
        const { userId } = req.params;
        
        const analysis = await PortfolioAnalysis.findOne({ userId })
            .sort({ lastAnalyzed: -1 });
        
        if (!analysis) {
            return res.status(404).json({
                success: false,
                message: 'Portfolio analysis not found for this user'
            });
        }

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

// Analyze user portfolio
const analyzePortfolio = async (req, res) => {
    try {
        const { userId } = req.params;
        
        const user = await User.findById(userId);
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }

        // Analyze portfolio based on user data
        const analysis = await performPortfolioAnalysis(user);
        
        // Save or update analysis
        const existingAnalysis = await PortfolioAnalysis.findOne({ userId });
        if (existingAnalysis) {
            await PortfolioAnalysis.findByIdAndUpdate(
                existingAnalysis._id,
                { ...analysis, lastAnalyzed: new Date() }
            );
        } else {
            const newAnalysis = new PortfolioAnalysis({
                userId,
                ...analysis,
                lastAnalyzed: new Date()
            });
            await newAnalysis.save();
        }

        res.status(200).json({
            success: true,
            message: 'Portfolio analysis completed successfully',
            data: analysis
        });
    } catch (error) {
        console.error('Analyze portfolio error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to analyze portfolio',
            error: error.message
        });
    }
};

// Perform portfolio analysis
const performPortfolioAnalysis = async (user) => {
    // This is a simplified analysis - you can enhance this with more sophisticated logic
    const analysis = {
        resumeScore: 0,
        skillGaps: [],
        recommendations: [],
        strengths: [],
        weaknesses: [],
        careerAlignment: {
            score: 0,
            suggestions: []
        }
    };

    // Analyze resume score based on user data
    let score = 0;
    if (user.personalDetails) score += 2;
    if (user.schoolDetails) score += 2;
    if (user.graduateDetails) score += 2;
    if (user.workingProfessionalDetails) score += 2;
    if (user.portfolio && user.portfolio.length > 0) score += 2;
    
    analysis.resumeScore = Math.min(score, 10);

    // Identify skill gaps based on career goals
    if (user.careerGoals && user.careerGoals.length > 0) {
        const careerGoal = user.careerGoals[0];
        analysis.skillGaps = [
            {
                skill: 'Technical Skills',
                importance: 'high',
                learningPath: 'Online courses and certifications',
                resources: ['Coursera', 'Udemy', 'edX']
            },
            {
                skill: 'Communication',
                importance: 'medium',
                learningPath: 'Practice and feedback',
                resources: ['Toastmasters', 'Online courses']
            }
        ];
    }

    // Generate recommendations
    analysis.recommendations = [
        {
            type: 'skill',
            title: 'Improve Technical Skills',
            description: 'Focus on learning relevant technical skills for your career goals',
            priority: 'high'
        },
        {
            type: 'certification',
            title: 'Get Industry Certifications',
            description: 'Obtain relevant certifications to boost your profile',
            priority: 'medium'
        },
        {
            type: 'project',
            title: 'Build Portfolio Projects',
            description: 'Create projects that showcase your skills',
            priority: 'high'
        }
    ];

    // Identify strengths and weaknesses
    analysis.strengths = ['Good educational background', 'Clear career goals'];
    analysis.weaknesses = ['Limited work experience', 'Need more technical skills'];

    // Career alignment analysis
    analysis.careerAlignment = {
        score: 7,
        suggestions: [
            'Align your skills with your career goals',
            'Focus on building relevant experience',
            'Network with professionals in your field'
        ]
    };

    return analysis;
};

// Get skill gap analysis
const getSkillGapAnalysis = async (req, res) => {
    try {
        const { userId } = req.params;
        
        const analysis = await PortfolioAnalysis.findOne({ userId })
            .select('skillGaps recommendations');
        
        if (!analysis) {
            return res.status(404).json({
                success: false,
                message: 'Portfolio analysis not found'
            });
        }

        res.status(200).json({
            success: true,
            data: {
                skillGaps: analysis.skillGaps,
                recommendations: analysis.recommendations
            }
        });
    } catch (error) {
        console.error('Get skill gap analysis error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get skill gap analysis',
            error: error.message
        });
    }
};

// Get career alignment analysis
const getCareerAlignment = async (req, res) => {
    try {
        const { userId } = req.params;
        
        const analysis = await PortfolioAnalysis.findOne({ userId })
            .select('careerAlignment strengths weaknesses');
        
        if (!analysis) {
            return res.status(404).json({
                success: false,
                message: 'Portfolio analysis not found'
            });
        }

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

module.exports = {
    getPortfolioAnalysis,
    analyzePortfolio,
    getSkillGapAnalysis,
    getCareerAlignment
};
