const ProjectModel = require('../../../models/ProjectModel')
const UserModel = require('../../../models/UserModel')
const getSearch = async (req, res, next) => {
  try {
    const { search, type, page = 1, limit = 10 } = req.query
    let result
    const selectedFields = '_id user_name first_name last_name user_type is_verified profile_image expertise  rate user_level user_score'
    let filter
    let totalPages
    let totalItems
    if (search) {
      if (!type) {
        res.status(422).json({ success: false, message: 'نوع جستجو را مشخص کنید' })
      } else if (type === 'project') {
        // جستجو در مدل Project با فیلتر کردن برای user_type === "employer"

        filter = { $or: [{ title: new RegExp(search, 'i'), status: 'accepted' }, { description: new RegExp(search, 'i'), status: 'accepted' }] }
        result = await ProjectModel.paginate(filter, { page: parseInt(page), limit: parseInt(limit), sort: { createdAt: -1 } })
        totalPages = result?.totalPages
        totalItems = result?.totalDocs
      } else if (type === 'user') {
        // جستجو در مدل User با فیلتر کردن برای user_type === "user"
        filter = { user_type: 'user', $or: [{ user_name: new RegExp(search, 'i') }, { first_name: new RegExp(search, 'i') }, { last_name: new RegExp(search, 'i') }] }
        result = await UserModel.paginate(filter, { page: parseInt(page), limit: parseInt(limit), select: selectedFields })
        totalPages = result?.totalPages
        totalItems = result?.totalDocs
      } else if (type === 'employer') {
        // جستجو در مدل User با فیلتر کردن برای user_type === "employer"
        filter = { user_type: 'employer', $or: [{ user_name: new RegExp(search, 'i') }, { first_name: new RegExp(search, 'i') }, { last_name: new RegExp(search, 'i') }] }
        result = await UserModel.paginate(filter, { page: parseInt(page), limit: parseInt(limit), select: selectedFields })
        totalPages = result?.totalPages
        totalItems = result?.totalDocs
      }
      res.status(200).json({
        success: true,
        result: result?.docs,
        type,
        totalPages,
        totalItems
      })
    } else {
      res.status(422).json({ success: false, message: 'چیزی تایپ کنید' })
    }
  } catch (error) {
    next(error)
  }
}

module.exports = {
  getSearch
}
