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

// Get job vs PG analysis for a specific field
const getJobVsPGAnalysis = async (req, res) => {
    try {
        const { field } = req.params;
        const { specialization } = req.query;

        const filter = { field, isActive: true };
        if (specialization) filter.specialization = specialization;

        const analysis = await JobVsPG.find(filter);

        if (analysis.length === 0) {
            return res.status(404).json({
                success: false,
                message: 'Job vs PG analysis not found for this field'
            });
        }

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

// Compare salary scenarios
const compareSalaryScenarios = async (req, res) => {
    try {
        const { field, specialization, currentStage } = req.body;

        const analysis = await JobVsPG.findOne({ 
            field, 
            specialization, 
            isActive: true 
        });

        if (!analysis) {
            return res.status(404).json({
                success: false,
                message: 'Analysis not found for this field and specialization'
            });
        }

        // Calculate break-even point
        const jobEarnings = analysis.comparison.jobAfterBtech.totalEarnings;
        const pgEarnings = analysis.comparison.pgAfterBtech.totalEarnings;
        
        let breakEvenYear = 0;
        for (let year = 1; year <= 5; year++) {
            if (pgEarnings[`year${year}`] > jobEarnings[`year${year}`]) {
                breakEvenYear = year;
                break;
            }
        }

        res.status(200).json({
            success: true,
            data: {
                field,
                specialization,
                currentStage,
                comparison: analysis.comparison,
                analysis: analysis.analysis,
                breakEvenYear,
                recommendation: breakEvenYear <= 3 ? 'PG is recommended' : 'Job is recommended'
            }
        });
    } catch (error) {
        console.error('Compare salary scenarios error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to compare salary scenarios',
            error: error.message
        });
    }
};

// Get career progression paths
const getCareerProgression = async (req, res) => {
    try {
        const { field } = req.params;

        const progression = await JobVsPG.find({ 
            field, 
            isActive: true 
        }).select('comparison analysis');

        if (progression.length === 0) {
            return res.status(404).json({
                success: false,
                message: 'Career progression not found for this field'
            });
        }

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

// Create job vs PG analysis (Admin only)
const createJobVsPGAnalysis = async (req, res) => {
    try {
        const analysisData = req.body;
        
        const analysis = new JobVsPG(analysisData);
        await analysis.save();

        res.status(201).json({
            success: true,
            message: 'Job vs PG analysis created successfully',
            data: analysis
        });
    } catch (error) {
        console.error('Create job vs PG analysis error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to create job vs PG analysis',
            error: error.message
        });
    }
};

// Update job vs PG analysis (Admin only)
const updateJobVsPGAnalysis = async (req, res) => {
    try {
        const { analysisId } = req.params;
        const updateData = req.body;

        const analysis = await JobVsPG.findByIdAndUpdate(
            analysisId,
            updateData,
            { new: true, runValidators: true }
        );

        if (!analysis) {
            return res.status(404).json({
                success: false,
                message: 'Job vs PG analysis not found'
            });
        }

        res.status(200).json({
            success: true,
            message: 'Job vs PG analysis updated successfully',
            data: analysis
        });
    } catch (error) {
        console.error('Update job vs PG analysis error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update job vs PG analysis',
            error: error.message
        });
    }
};

module.exports = {
    getJobVsPGAnalysis,
    compareSalaryScenarios,
    getCareerProgression,
    createJobVsPGAnalysis,
    updateJobVsPGAnalysis
};
