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

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

export default apiHandler({
     post: checkCode,
});

async function checkCode(req, res) {
     const userID = req.userID;
     const { code } = req.body;

     if (!userID) {
          return res.status(400).json({ error: 'User ID is required' });
     }

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

     try {
          const userData = await db.User.findByPk(userID);

          if (!userData) {
               return res.status(404).json({ error: 'User not found' });
          }

          const promotionCode = await stripe.promotionCodes.list({
               code: code,
               limit: 1
          });

          if (promotionCode.data.length === 0) {
               return res.status(404).json({ error: 'No code available.' });
          }

          const promotion = promotionCode.data[0];

          if (!promotion.active) {
               return res.status(404).json({ error: 'Codul nu a fost validat deoarece nu mai este activ.' });
          }

          if (promotion.times_redeemed >= promotion.max_redemptions) {
               return res.status(404).json({ error: 'Codul nu a fost validat deoarece a fost atinsa limita permisa de activari.' });
          }
          
          return res.status(200).json({ 
               status: 200, 
               message: 'Codul a fost validat si aplicat cu succes pentru comanda ta!', 
               code: promotion.code, 
               percentageDiscount: promotion.coupon.percent_off 
          });

     } catch (error) {
          console.error(error);
          return res.status(500).json({ error: 'Internal server error', status: 500 });
     }
}
