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

// Get mentors by expertise
const getMentors = async (req, res) => {
    try {
        const { expertise, page = 1, limit = 10 } = req.query;
        
        const filter = { isActive: true };
        if (expertise) filter.expertise = { $in: [expertise] };

        const mentors = await Mentor.find(filter)
            .select('-__v')
            .sort({ 'rating.average': -1 })
            .limit(limit * 1)
            .skip((page - 1) * limit);

        const total = await Mentor.countDocuments(filter);

        res.status(200).json({
            success: true,
            data: {
                mentors,
                pagination: {
                    currentPage: parseInt(page),
                    totalPages: Math.ceil(total / limit),
                    totalMentors: total,
                    hasNext: page < Math.ceil(total / limit),
                    hasPrev: page > 1
                }
            }
        });
    } catch (error) {
        console.error('Get mentors error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get mentors',
            error: error.message
        });
    }
};

// Get mentor details
const getMentorDetails = async (req, res) => {
    try {
        const { mentorId } = req.params;
        
        const mentor = await Mentor.findById(mentorId);
        
        if (!mentor) {
            return res.status(404).json({
                success: false,
                message: 'Mentor not found'
            });
        }

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

// Get mentor expertise areas
const getMentorExpertise = async (req, res) => {
    try {
        const expertise = await Mentor.distinct('expertise', { isActive: true });
        
        res.status(200).json({
            success: true,
            data: expertise
        });
    } catch (error) {
        console.error('Get mentor expertise error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get mentor expertise',
            error: error.message
        });
    }
};

// Book mentor consultation
const bookMentorConsultation = async (req, res) => {
    try {
        const { mentorId } = req.params;
        const { userId, preferredDate, preferredTime, message } = req.body;

        const mentor = await Mentor.findById(mentorId);
        
        if (!mentor) {
            return res.status(404).json({
                success: false,
                message: 'Mentor not found'
            });
        }

        // Check if mentor is available
        if (!mentor.availability.days.includes(preferredDate) || 
            !mentor.availability.timeSlots.includes(preferredTime)) {
            return res.status(400).json({
                success: false,
                message: 'Mentor is not available at the requested time'
            });
        }

        // Create consultation booking (you might want to create a separate model for this)
        const consultation = {
            mentorId,
            userId,
            preferredDate,
            preferredTime,
            message,
            status: 'pending',
            createdAt: new Date()
        };

        res.status(200).json({
            success: true,
            message: 'Consultation booking request sent successfully',
            data: consultation
        });
    } catch (error) {
        console.error('Book mentor consultation error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to book mentor consultation',
            error: error.message
        });
    }
};

// Create mentor (Admin only)
const createMentor = async (req, res) => {
    try {
        const mentorData = req.body;
        
        const mentor = new Mentor(mentorData);
        await mentor.save();

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

// Update mentor (Admin only)
const updateMentor = async (req, res) => {
    try {
        const { mentorId } = req.params;
        const updateData = req.body;

        const mentor = await Mentor.findByIdAndUpdate(
            mentorId,
            updateData,
            { new: true, runValidators: true }
        );

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

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

module.exports = {
    getMentors,
    getMentorDetails,
    getMentorExpertise,
    bookMentorConsultation,
    createMentor,
    updateMentor
};
