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

// Get industry analysis
const getIndustryAnalysis = async (req, res) => {
    try {
        const { industry } = req.params;
        
        const analysis = await IndustryAnalysis.findOne({ 
            industry, 
            isActive: true 
        });
        
        if (!analysis) {
            return res.status(404).json({
                success: false,
                message: 'Industry analysis not found'
            });
        }

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

// Get all industries
const getAllIndustries = async (req, res) => {
    try {
        const industries = await IndustryAnalysis.find({ isActive: true })
            .select('industry description futureOutlook.demand futureOutlook.growth')
            .sort({ industry: 1 });

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

// Get industry switching guidance
const getIndustrySwitching = async (req, res) => {
    try {
        const { fromIndustry, toIndustry } = req.query;

        if (!fromIndustry || !toIndustry) {
            return res.status(400).json({
                success: false,
                message: 'From industry and to industry are required'
            });
        }

        const switching = await IndustryAnalysis.findOne({
            industry: toIndustry,
            'industrySwitching.fromIndustry': fromIndustry,
            isActive: true
        });

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

        const switchingData = switching.industrySwitching.find(
            s => s.fromIndustry === fromIndustry && s.toIndustry === toIndustry
        );

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

// Get job roles for an industry
const getIndustryJobRoles = async (req, res) => {
    try {
        const { industry } = req.params;
        
        const analysis = await IndustryAnalysis.findOne({ 
            industry, 
            isActive: true 
        }).select('jobRoles salaryTrends');

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

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

// Get future outlook for industries
const getFutureOutlook = async (req, res) => {
    try {
        const { demand, growth, aiImpact } = req.query;
        
        const filter = { isActive: true };
        if (demand) filter['futureOutlook.demand'] = demand;
        if (growth) filter['futureOutlook.growth'] = growth;
        if (aiImpact) filter['futureOutlook.aiImpact'] = aiImpact;

        const industries = await IndustryAnalysis.find(filter)
            .select('industry futureOutlook emergingFields')
            .sort({ 'futureOutlook.demand': -1 });

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

// Create industry analysis (Admin only)
const createIndustryAnalysis = async (req, res) => {
    try {
        const analysisData = req.body;
        
        const analysis = new IndustryAnalysis(analysisData);
        await analysis.save();

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

// Update industry analysis (Admin only)
const updateIndustryAnalysis = async (req, res) => {
    try {
        const { analysisId } = req.params;
        const updateData = req.body;

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

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

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

module.exports = {
    getIndustryAnalysis,
    getAllIndustries,
    getIndustrySwitching,
    getIndustryJobRoles,
    getFutureOutlook,
    createIndustryAnalysis,
    updateIndustryAnalysis
};
