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

// Get all decision trees (Admin)
const getAllDecisionTrees = async (req, res) => {
    try {
        const decisionTrees = await DecisionTree.find({}).sort({ createdAt: -1 });

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

// Get decision tree for a specific stage
const getDecisionTree = async (req, res) => {
    try {
        const { stage } = req.params;
        
        const decisionTree = await DecisionTree.findOne({ 
            stage, 
            isActive: true 
        });

        if (!decisionTree) {
            return res.status(404).json({
                success: false,
                message: 'Decision tree not found for this stage'
            });
        }

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

// Navigate through decision tree
const navigateDecisionTree = async (req, res) => {
    try {
        const { stage, currentNode, selectedOption } = req.body;
        
        const decisionTree = await DecisionTree.findOne({ 
            stage, 
            isActive: true 
        });

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

        // Find the next node based on selected option
        const nextNode = decisionTree.nextNodes.find(node => 
            node.nodeId === selectedOption
        );

        if (!nextNode) {
            return res.status(400).json({
                success: false,
                message: 'Invalid option selected'
            });
        }

        // Get related content based on the path
        const relatedContent = await getRelatedContent(stage, selectedOption);

        res.status(200).json({
            success: true,
            data: {
                currentNode: nextNode.nodeId,
                label: nextNode.label,
                description: nextNode.description,
                isEndNode: nextNode.isEndNode,
                relatedContent
            }
        });
    } catch (error) {
        console.error('Navigate decision tree error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to navigate decision tree',
            error: error.message
        });
    }
};

// Get related content for a selected path
const getRelatedContent = async (stage, path) => {
    // This would integrate with your existing career paths, exams, etc.
    // For now, returning mock data
    return {
        articles: [
            {
                title: `Guide to ${path} Career`,
                url: '#',
                description: 'Comprehensive guide to building a career in this field'
            }
        ],
        videos: [
            {
                title: `${path} Career Path Explained`,
                url: '#',
                duration: '10:30'
            }
        ],
        tips: [
            'Start building relevant skills early',
            'Network with professionals in the field',
            'Stay updated with industry trends'
        ],
        networkSuggestions: {
            peers: 'Join study groups for this field',
            alumni: 'Connect with alumni who pursued this path',
            mentors: 'Find mentors in this industry'
        },
        examSuggestions: [
            'Relevant entrance exams',
            'Certification programs',
            'Skill assessments'
        ],
        careerFairs: [
            'Industry-specific career fairs',
            'Networking events',
            'Job expos'
        ]
    };
};

// Create decision tree (Admin only)
const createDecisionTree = async (req, res) => {
    try {
        const decisionTreeData = req.body;
        
        const decisionTree = new DecisionTree(decisionTreeData);
        await decisionTree.save();

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

// Update decision tree (Admin only)
const updateDecisionTree = async (req, res) => {
    try {
        const { treeId } = req.params;
        const updateData = req.body;

        const decisionTree = await DecisionTree.findByIdAndUpdate(
            treeId,
            updateData,
            { new: true, runValidators: true }
        );

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

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

module.exports = {
    getAllDecisionTrees,
    getDecisionTree,
    navigateDecisionTree,
    createDecisionTree,
    updateDecisionTree
};
