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

export default apiHandler({
     post: updateCourseStatus, 
     delete: deleteCourse, 
});

async function updateCourseStatus(req, res) {
     const userID = req.userID;
     const { courseID } = req.body;

     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 = [];

          await db.Courses.update(
               { waiting: 0 },
               { 
                 where: { id: courseID } 
               }
          );

          responseArray.push({ message: 'Cursul a fost actualizat. '});

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

async function deleteCourse(req, res) {
     const userID = req.userID;
     const { courseID } = req.body;

     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 = [];

          await db.Courses.delete({
               where: {
                    id: courseID
               }
          });

          responseArray.push({ message: 'Cursul a fost sters. '});

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