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

// Get all exams (Admin only)
const getAllExams = async (req, res) => {
    try {
        const { page = 1, limit = 50, stage, category, isActive } = req.query;

        const filter = {};

        if (stage) filter.stage = stage;
        if (category) filter.category = category;
        if (isActive !== undefined) filter.isActive = isActive === 'true';

        const exams = await Exam.find(filter)
            .select('-__v')
            .sort({ createdAt: -1 })
            .limit(limit * 1)
            .skip((page - 1) * limit);

        const total = await Exam.countDocuments(filter);

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

// Get all exams for a specific stage
const getExamsByStage = async (req, res) => {
    try {
        const { stage } = req.params;
        const { category, page = 1, limit = 10 } = req.query;

        const filter = { 
            stage,
            isActive: true 
        };

        if (category) {
            filter.category = category;
        }

        const exams = await Exam.find(filter)
            .select('-__v')
            .sort({ name: 1 })
            .limit(limit * 1)
            .skip((page - 1) * limit);

        const total = await Exam.countDocuments(filter);

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

// Get specific exam details
const getExamDetails = async (req, res) => {
    try {
        const { examId } = req.params;

        const exam = await Exam.findById(examId);

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

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

// Search exams
const searchExams = async (req, res) => {
    try {
        const { query, stage, category } = req.query;
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;

        const filter = { isActive: true };

        if (query) {
            filter.$or = [
                { name: { $regex: query, $options: 'i' } },
                { fullForm: { $regex: query, $options: 'i' } },
                { conductingBody: { $regex: query, $options: 'i' } }
            ];
        }

        if (stage) filter.stage = stage;
        if (category) filter.category = category;

        const exams = await Exam.find(filter)
            .select('-__v')
            .sort({ name: 1 })
            .limit(limit)
            .skip((page - 1) * limit);

        const total = await Exam.countDocuments(filter);

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

// Get upcoming exams
const getUpcomingExams = async (req, res) => {
    try {
        const { stage } = req.query;
        const currentDate = new Date();

        const filter = {
            isActive: true,
            'importantDates.examDate': { $gte: currentDate }
        };

        if (stage) filter.stage = stage;

        const exams = await Exam.find(filter)
            .select('name fullForm importantDates.applicationEnd importantDates.examDate stage')
            .sort({ 'importantDates.examDate': 1 })
            .limit(20);

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

// Get exam categories
const getExamCategories = async (req, res) => {
    try {
        const categories = await Exam.aggregate([
            { $match: { isActive: true } },
            { $group: { _id: '$category', count: { $sum: 1 } } },
            { $sort: { count: -1 } }
        ]);

        const stages = await Exam.aggregate([
            { $match: { isActive: true } },
            { $group: { _id: '$stage', count: { $sum: 1 } } },
            { $sort: { count: -1 } }
        ]);

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

// Add new exam (Admin only)
const addExam = async (req, res) => {
    try {
        const examData = req.body;

        const exam = new Exam(examData);
        await exam.save();

        res.status(201).json({
            success: true,
            message: 'Exam added successfully',
            data: exam
        });
    } catch (error) {
        console.error('Add exam error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to add exam',
            error: error.message
        });
    }
};

// Update exam (Admin only)
const updateExam = async (req, res) => {
    try {
        const { examId } = req.params;
        const updateData = req.body;

        const exam = await Exam.findByIdAndUpdate(
            examId,
            updateData,
            { new: true, runValidators: true }
        );

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

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

// Delete exam (Admin only)
const deleteExam = async (req, res) => {
    try {
        const { examId } = req.params;

        const exam = await Exam.findByIdAndDelete(examId);

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

        res.status(200).json({
            success: true,
            message: 'Exam deleted successfully'
        });
    } catch (error) {
        console.error('Delete exam error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to delete exam',
            error: error.message
        });
    }
};

module.exports = {
    getAllExams,
    getExamsByStage,
    getExamDetails,
    searchExams,
    getUpcomingExams,
    getExamCategories,
    addExam,
    updateExam,
    deleteExam
};
