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

async function handler(req, res) {
  const { method } = req;

  await dbConnect();

  const pageIndex = req.query.page;

  if (pageIndex < 1) {
    res.status(422).json({
      message: 'Page does not exist ',
    });
    return;
  }

  switch (method) {
    case 'GET': {
      try {
        const productCount = await Product.countDocuments();

        if (productCount === 0) {
          res.status(200).json({
            message: 'There are currently no products in our database.',
            Product: [],
            ProductCount: 0,
          });
          break;
        }

        if ((pageIndex - 1) * 4 >= productCount) {
          throw new Error('Page does not exist!');
        }

        const product = await Product.find({})
          .skip((pageIndex - 1) * 4)
          .limit(4);

        if (!product) {
          throw new Error('There are currently no products in our database.');
        }

        res.status(200).json({
          message: 'All products from our database were fetched successfully.',
          product,
          productCount,
        });
      } catch (error) {
        res.status(400).json({ message: error.message });
      }
      break;
    }
    case 'POST': {
      try {
        const product = await Product.create(req.body);
        res
          .status(201)
          .json({ message: 'Your product was created and stored!', product });
      } catch (error) {
        res.status(400).json({ success: false });
      }
      break;
    }
    default:
      res.status(405).json({ message: 'Method not allowed' });
      break;
  }
}

export default handler;
