import { Error } from 'mongoose'
import { NextApiRequest, NextApiResponse } from 'next'
import { Booking } from '../../../db/booking'
import { createBooking } from '../../../db/index'
import { sendReceivedBookingMail } from '../../../helpers/mail'

export default async function userHandler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { method } = req

  let booking: Booking

  switch (method) {
    case 'POST':
      try {
        booking = await createBooking(req.body)
        res.status(200).json(booking)
      } catch (e) {
        console.error(e)
        if (e instanceof Error.ValidationError) {
          res.status(400).json({ message: e.message, errors: e.errors })
          return
        }
        res.status(500).end(`Internal Server Error...Guru is meditating...`)
        return
      }

      await sendReceivedBookingMail(booking)
      console.log('sent receivedBookingMail')
      break
    default:
      res.setHeader('Allow', ['POST'])
      res.status(405).end(`Method ${method} Not Allowed`)
  }
}
