import type { NextApiRequest, NextApiResponse } from 'next';
import dbConnect from '../../../utils/helpers/dbHelpers';
import { UpdateResponse, IUser } from '../../../utils/interface/userInterface';
const User = require('../../../models/user');

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

  await dbConnect();

  switch (method) {
    case 'POST': {
      try {
        const user: IUser = await User.create(req.body);
        res
          .status(201)
          .json({ message: `User (${user.fullName}) created sucessfully!` });
      } 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;
