import { Error } from 'mongoose' import { NextApiRequest, NextApiResponse } from 'next' import { Booking } from '../../../db/booking' import { createBooking } from '../../../db/index' import { log } from '../../../helpers/log' import { sendReceivedBookingAdminMail, sendReceivedBookingBookerMail, } from '../../../helpers/mail' export default async function userHandler( req: NextApiRequest, res: NextApiResponse ): Promise { const { method } = req let booking: Booking switch (method) { case 'POST': try { booking = await createBooking(req.body) } catch (e) { if (e instanceof Error.ValidationError) { res.status(400).json({ message: e.message, errors: e.errors }) return } log.error('Failed to store booking', e) res.status(500).end(`Internal Server Error...Guru is meditating...`) return } log.info( `received booking ${booking.uuid} from ${booking.email}`, booking ) try { await sendReceivedBookingAdminMail(booking) log.info(`send booking ${booking.uuid} received to admin`, booking) } catch (error) { log.error(`failed to send booking ${booking.uuid} received to admin`, booking) } try { await sendReceivedBookingBookerMail(booking) log.info( `send booking ${booking.uuid} received to {booking.email}`, booking ) } catch (error) { log.error( `failed to send booking ${booking.uuid} received to {booking.email}`, booking ) } res.status(200).json(booking) break default: res.setHeader('Allow', ['POST']) res.status(405).end(`Method ${method} Not Allowed`) } }