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

// Get all interests
const getAllInterests = async (req, res) => {
    try {
        const { category, isActive, search } = req.query;
        
        // Build filter object
        const filter = {};
        
        if (category) {
            filter.category = new RegExp(category, 'i');
        }
        
        if (isActive !== undefined) {
            filter.isActive = isActive === 'true';
        }
        
        if (search) {
            filter.$or = [
                { name: new RegExp(search, 'i') },
                { description: new RegExp(search, 'i') },
                { category: new RegExp(search, 'i') }
            ];
        }
        
        // Get all interests without pagination
        const interests = await Interests.find(filter)
            .sort({ name: 1 })
            .select('-__v');
        
        res.status(200).json({
            success: true,
            data: interests,
            count: interests.length
        });
    } catch (error) {
        console.error('Error fetching interests:', error);
        res.status(500).json({
            success: false,
            message: 'Error fetching interests',
            error: error.message
        });
    }
};

// Get interests by category
const getInterestsByCategory = async (req, res) => {
    try {
        const { category } = req.params;
        
        const interests = await Interests.find({ 
            category: new RegExp(category, 'i'),
            isActive: true 
        })
        .sort({ name: 1 })
        .select('-__v');
        
        res.status(200).json({
            success: true,
            data: interests,
            count: interests.length
        });
    } catch (error) {
        console.error('Error fetching interests by category:', error);
        res.status(500).json({
            success: false,
            message: 'Error fetching interests by category',
            error: error.message
        });
    }
};

// Get single interest by ID
const getInterestById = async (req, res) => {
    try {
        const { id } = req.params;
        
        const interest = await Interests.findById(id).select('-__v');
        
        if (!interest) {
            return res.status(404).json({
                success: false,
                message: 'Interest not found'
            });
        }
        
        res.status(200).json({
            success: true,
            data: interest
        });
    } catch (error) {
        console.error('Error fetching interest by ID:', error);
        res.status(500).json({
            success: false,
            message: 'Error fetching interest',
            error: error.message
        });
    }
};

// Get all categories
const getCategories = async (req, res) => {
    try {
        const categories = await Interests.distinct('category', { isActive: true });
        
        res.status(200).json({
            success: true,
            data: categories.sort()
        });
    } catch (error) {
        console.error('Error fetching categories:', error);
        res.status(500).json({
            success: false,
            message: 'Error fetching categories',
            error: error.message
        });
    }
};

// Create new interest (Admin only)
const createInterest = async (req, res) => {
    try {
        const { name, category, description } = req.body;
        
        // Check if interest already exists
        const existingInterest = await Interests.findOne({ 
            name: new RegExp(`^${name}$`, 'i') 
        });
        
        if (existingInterest) {
            return res.status(400).json({
                success: false,
                message: 'Interest with this name already exists'
            });
        }
        
        const newInterest = new Interests({
            name: name.trim(),
            category: category.trim(),
            description: description?.trim()
        });
        
        await newInterest.save();
        
        res.status(201).json({
            success: true,
            message: 'Interest created successfully',
            data: newInterest
        });
    } catch (error) {
        console.error('Error creating interest:', error);
        res.status(500).json({
            success: false,
            message: 'Error creating interest',
            error: error.message
        });
    }
};

// Update interest (Admin only)
const updateInterest = async (req, res) => {
    try {
        const { id } = req.params;
        const { name, category, description, isActive } = req.body;
        
        const interest = await Interests.findById(id);
        
        if (!interest) {
            return res.status(404).json({
                success: false,
                message: 'Interest not found'
            });
        }
        
        // Check if name is being changed and if it conflicts
        if (name && name !== interest.name) {
            const existingInterest = await Interests.findOne({ 
                name: new RegExp(`^${name}$`, 'i'),
                _id: { $ne: id }
            });
            
            if (existingInterest) {
                return res.status(400).json({
                    success: false,
                    message: 'Interest with this name already exists'
                });
            }
        }
        
        // Update fields
        if (name) interest.name = name.trim();
        if (category) interest.category = category.trim();
        if (description !== undefined) interest.description = description?.trim();
        if (isActive !== undefined) interest.isActive = isActive;
        
        await interest.save();
        
        res.status(200).json({
            success: true,
            message: 'Interest updated successfully',
            data: interest
        });
    } catch (error) {
        console.error('Error updating interest:', error);
        res.status(500).json({
            success: false,
            message: 'Error updating interest',
            error: error.message
        });
    }
};

// Delete interest (Admin only)
const deleteInterest = async (req, res) => {
    try {
        const { id } = req.params;
        
        const interest = await Interests.findByIdAndDelete(id);
        
        if (!interest) {
            return res.status(404).json({
                success: false,
                message: 'Interest not found'
            });
        }
        
        res.status(200).json({
            success: true,
            message: 'Interest deleted successfully'
        });
    } catch (error) {
        console.error('Error deleting interest:', error);
        res.status(500).json({
            success: false,
            message: 'Error deleting interest',
            error: error.message
        });
    }
};

module.exports = {
    getAllInterests,
    getInterestsByCategory,
    getInterestById,
    getCategories,
    createInterest,
    updateInterest,
    deleteInterest
};
