const Product = require('../../../models/product');
import dbConnect from '../../../utils/helpers/dbHelpers';
import type { NextApiRequest, NextApiResponse } from 'next';
import {
  ProductDataDB,
  ProductsResponse,
} from '../../../utils/interface/productInterface';

async function handler(
  req: NextApiRequest,
  res: NextApiResponse<ProductsResponse>
) {
  const { method } = req;

  await dbConnect();

  const pageIndex = parseInt(req.query.pageIndex as string);
  const category = req.query.category === 'All' ? '' : req.query.category;
  const filterType = req.query.filterType;

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

  switch (method) {
    case 'GET': {
      try {
        const productCount: number = await Product.find({
          category: { $regex: category },
        }).countDocuments();

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

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

        const product: Array<ProductDataDB> = await Product.find({
          category: { $regex: category },
        })
          .skip((pageIndex - 1) * 9)
          .limit(9)
          .sort(filterType === 'asc' ? 'name' : '-name ');

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

        const previousUrl =
          pageIndex > 1
            ? `https://localhost:3000/api/product?pageIndex=${pageIndex - 1}`
            : '';
        const nextUrl =
          pageIndex * 9 < productCount
            ? `https://localhost:3000/api/product?pageIndex=${pageIndex + 1}`
            : '';

        res.status(200).json({
          message: 'All products from our database were fetched successfully.',
          product,
          productCount,
          next: nextUrl,
          previous: previousUrl,
        });
      } catch (error) {
        if (error instanceof Error)
          res.status(400).json({ message: error.message });
        else res.status(400).json({ message: 'Unexpected error' + error });
      }
      break;
    }
    case 'POST': {
      try {
        const product: ProductDataDB = await Product.create(req.body);
        res
          .status(201)
          .json({ message: 'Your product was created and stored!', product });
      } catch (error) {
        if (error instanceof Error)
          res.status(400).json({ message: error.message });
        else res.status(400).json({ message: 'Unexpected error' + error });
      }
      break;
    }
    default:
      res.status(405).json({ message: 'Method not allowed' });
      break;
  }
}

export default handler;
