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

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

  await dbConnect();

  switch (method) {
    case 'GET': {
      try {
        const featuredProducts: Array<ProductDataDB> = await Product.find({
          isFeatured: true,
        });

        if (!featuredProducts) {
          res.status(200).json({
            message: 'There are no featured products right now.',
            featuredProducts: [],
          });
        }

        res.status(200).json({
          message: 'Featured products were fetched successfully.',
          featuredProducts,
        });
      } 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;
