const Product = require('../../../../models/product');
import dbConnect from '../../../../utils/helpers/dbHelpers';

async function handler(req, res) {
  const { method } = req;
  const categoryName = req.query.categoryName;
  await dbConnect();

  switch (method) {
    case 'GET': {
      try {
        const productsByCategory = await Product.find({
          category: categoryName,
        });

        if (!productsByCategory) {
          res.status(200).json({
            message:
              'There are currently no products in our database for the selected category.',
            productsByCategory: [],
          });
        }

        res.status(200).json({
          message:
            'All products from our database for the selected category were fetched successfully.',
          productsByCategory,
        });
      } catch (error) {
        res.status(400).json({ message: error.message });
      }
      break;
    }
    default:
      res.status(405).json({ message: 'Method not allowed' });
      break;
  }
}

export default handler;
