const User     = require('../models/user');
const Car      = require('../models/cars');
const Post     = require('../models/post');

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

    // kick off all three searches in parallel
    const [ users, cars, posts ] = await Promise.all([
      User.find({ username: { $regex: q, $options: 'i' } })
        .select('username profile_pic')
        .limit(5)
        .lean(),

      Car.find({
        $or: [
          { make:  { $regex: q, $options: 'i' } },
          { model: { $regex: q, $options: 'i' } }
        ]
      })
      .select('make model year image')
      .limit(5)
      .lean(),

      Post.find({ content: { $regex: q, $options: 'i' } })
        .populate('user_id', 'username profile_pic')
        .sort({ timestamp: -1 })
        .limit(5)
        .lean()
    ]);

    const host     = req.get('host');
    const protocol = req.protocol;

    // map into a unified result shape
    const userResults = users.map(u => ({
      type:     'user',
      id:       u._id,
      username: u.username,
      avatar:   `${protocol}://${host}${u.profile_pic}`,
    }));

    const carResults = cars.map(c => ({
      type:  'car',
      id:    c._id,
      title: `${c.make} ${c.model} (${c.year})`,
      image: `${protocol}://${host}${c.image}`,
    }));

    const postResults = posts.map(p => ({
      type:    'post',
      id:      p._id,
      snippet: p.content.slice(0, 50) + (p.content.length > 50 ? '…' : ''),
      image:   p.image
                ? `${protocol}://${host}${p.image}`
                : null,
      author:  p.user_id.username,
    }));

    // return a single combined array
    return res.json([
      ...userResults,
      ...carResults,
      ...postResults
    ]);

  } catch (err) {
    console.error('searchAll error:', err);
    return res.status(500).json({ message: err.message });
  }
};
