const Student = require('../models/Student');
const Book = require('../models/Book');

exports.search = async (req, res) => {
  try {
    const q = (req.query.q || '').trim();
    if (!q) {
      return res.status(400).json({ msg: 'Search query is required' });
    }

    const regex = new RegExp(q, 'i');

    const students = await Student.find({
      $or: [
        { name: regex },
        { studentClass: regex },
        { email: regex },
        { phone: regex },
      ],
    });

    const books = await Book.find({
      $or: [{ title: regex }, { author: regex }],
    });

    res.status(200).json({ students, books });
  } catch (error) {
    res.status(500).json({ msg: 'Search failed', error: error.message });
  }
};
