import { apiHandler, db } from '@/helpers/api';
import { Op } from 'sequelize';

export default apiHandler({
     get: getUsers
});

async function getUsers(req, res) {
     const userID = req.userID;

     if(!db.initialized)
          await db.initialize(); 

     try {
          const userData = await db.User.findByPk(userID); 
          
          if (!userData) 
               return res.status(404).json({ error: 'Unknown!' });

          if(userData.admin == 0) 
               return res.status(401).json({error:'Not authorized'}); 

          const responseArray = [];

          const { searchTerm } = req.query;

          const searchConditions = searchTerm.length >= 2
          ? {
               [Op.or]: [
                    { userName: { [Op.like]: `%${searchTerm}%` } },
                    { firstName: { [Op.like]: `%${searchTerm}%` } },
                    { surName: { [Op.like]: `%${searchTerm}%` } },
                    { email: { [Op.like]: `%${searchTerm}%` } },
               ],
            }
          : {};

          let studentCount = await db.User.findAll();

          if(searchTerm.length >= 2) {
               studentCount = await db.User.findAll({
                    where: searchConditions
               });
          }

          const courseList = await db.Courses.findAll({
               where: {
                    waiting: 1
               }
          });

          responseArray.push({
               userList: studentCount, 
               coursesList: courseList, 
          });

          return res.status(200).json(responseArray);
     } catch (error) {
          return res.status(500).json({ error: 'Eroare la preluarea datelor utilizatorului.' });
     }
}