const Order = require('../../../models/order');
import dbConnect from '../../../utils/helpers/dbHelpers';
import { Types } from 'mongoose';
import type { NextApiRequest, NextApiResponse } from 'next';
import {
  OrderResponse,
  OrderDataDB,
} from '../../../utils/interface/orderInterface';

async function handler(
  req: NextApiRequest,
  res: NextApiResponse<OrderResponse>
) {
  const { method } = req;
  const ownerID = req.query.ownerID as string;
  await dbConnect();

  switch (method) {
    case 'POST': {
      try {
        const order: OrderDataDB = await Order.create(
          req.body
        ); /* create a new model in the database */
        res
          .status(201)
          .json({ message: 'Your order was submitted successfully!', order });
      } catch (error) {
        if (error instanceof Error)
          res.status(400).json({ message: error.message });
        else res.status(400).json({ message: 'Unexpected error' + error });
      }
      break;
    }
    case 'GET': {
      try {
        const objectId = new Types.ObjectId(ownerID);
        const orders: Array<OrderDataDB> = await Order.find({
          owner: objectId,
        });
        if (!orders) {
          res.status(200).json({
            message:
              'There are currently no orders in our database for the selected owner.',
            orders: [],
          });
        }

        res.status(200).json({
          message:
            'All orders from our database for the selected owner were fetched successfully.',
          orders,
        });
      } 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;
