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

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

  await dbConnect();

  switch (method) {
    case 'GET': {
      try {
        const productId = req.query.productId;

        const product: ProductDataDB = await Product.findOne({
          customID: productId,
        });

        if (!product) {
          throw new Error('The product with this id does not exist!');
        }

        const similarProducts: Array<ProductDataDB> = await Product.find({
          category: product.category,
          customID: { $ne: product.customID },
        });

        const shuffled = similarProducts
          .sort(() => 0.5 - Math.random())
          .slice(0, 3);

        res.status(200).json({
          message: 'The product you requested was fetched successfully.',
          product,
          similarProducts: shuffled,
        });
      } 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;
