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

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

  await dbConnect();

  switch (method) {
    case 'PATCH': {
      const updates = Object.keys(req.body.userData);
      const allowedUpdates = [
        'fullName',
        'email',
        'address',
        'address2',
        'city',
        'country',
        'postcode',
      ];
      const isValidOperation = updates.every((update) =>
        allowedUpdates.includes(update)
      );

      if (!isValidOperation) {
        return res.status(400).send({ message: 'Invalid updates!' });
      }

      try {
        const user = await User.findOne({ _id: req.body._id });
        updates.forEach((update) => (user[update] = req.body.userData[update]));
        await user.save();
        res.send({
          message: 'User profile updated successfully.',
        });
      } catch (error) {
        if (error instanceof Error)
          res.status(400).json({ message: error.message });
        else res.status(400).json({ message: 'Unexpected error' + error });
      }
      break;
    }
  }
}

export default handler;
