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

export default apiHandler({
    post: verifyOrder
});

const stripe = require('stripe')('sk_test_51Py980Js2Gbkz0QXEMr6KizB1SUz3LKWbCCTvEIGQruzwEzOQuT5JfBwG3ySGLyGKBKRqf6lrk4YwtLisTpqtB3a00aLYFykKT');

async function verifyOrder(req, res) {
     const realUserID = req.userID;
     const sessionId = req.body.sessionId;
     const insertedUserID = req.body.userID;

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

     try {
   
          if (realUserID != insertedUserID) {
               console.log(`User ID mismatch: realUserID=${realUserID}, insertedUserID=${insertedUserID}`);
               return res.status(200).json({ page: '/problem-order', problemID: 1 });
          }

          const userData = await db.User.findByPk(realUserID);

          if (!userData) {
               console.log(`User not found for ID=${realUserID}`);
               return res.status(200).json({ page: '/problem-order', problemID: 2 });
          }

          const session = await stripe.checkout.sessions.retrieve(sessionId);

          if (session.payment_status === 'paid') {
               const formData = session.metadata;

               const cartProductIdsArray = formData.cartProducts.split(',').map(id => parseInt(id, 10));

               const products = await db.Courses.findAll({
                    attributes: ['id', 'title', 'price', 'priceReduced'],
                    where: {
                         id: cartProductIdsArray
                    },
                    limit: cartProductIdsArray.length,
                    raw: true,
               });

               for (const product of products) {
                    await db.Orders.create({
                         userID: realUserID,
                         courseName: product.title,
                         price: (product.priceReduced) ? (product.priceReduced) : (product.price),
                    });

                    const courseLessons = await db.Modules.findAll({
                         attributes: ['duration', 'title'], 
                         where: {
                              courseID: product.id,
                              type: 'lesson',
                         },
                         limit: 10,
                         raw: true
                    });

                    console.log("test1"); 

                    const jsonProgress = courseLessons.map(lesson => ({
                         watchedSeconds: 0,
                         neededSeconds: lesson.duration,
                         name: lesson.title,
                         completed: false
                    }));

                    const courseModules = await db.Modules.findAll({
                         attributes:['id'], 
                         where: {
                              courseID: product.id, 
                              type: 'module'
                         },
                         limit: 15
                    });  

                    const jsonProgress2 = courseModules.map(module => ({
                         module: module.id,
                         quizCompleted: false
                    }));
                    console.log("test2"); 
                    const process = await db.CoursesProgress.create({
                         userID: realUserID, 
                         courseID: product.id, 
                         courseName: product.title, 
                         courseProgress: JSON.stringify(jsonProgress),
                         quizProgress: JSON.stringify(jsonProgress2)
                    });
                    console.log(process); 
                    console.log("integrat"); 
               }
           
               await db.Cart.destroy({
                    where: { forID: realUserID }
               });

               return res.status(200).json({ page: '/profil-student/istoric-comenzi' });
          } else {
               return res.status(200).json({ page: '/problem-order', problemID: 3 });
          }
     } catch (error) {
          return res.status(200).json({ page: '/problem-order', problemID: 4 });
     }
}