const Person = require('../../models/person');
import dbConnect from '../../utils/helpers/dbHelpers';
import type { NextApiRequest, NextApiResponse } from 'next';
import { IPerson, PersonRespone } from '../../utils/interface/personInterface';

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

  await dbConnect();

  const pageIndex = parseInt(req.query.page ? req.query.page.toString() : '0');

  if (pageIndex < 1) {
    res.status(422).json({
      message: 'Page does not exist ',
    });
    return;
  }

  switch (method) {
    case 'GET': {
      try {
        const dataCount: number = await Person.countDocuments();

        if (dataCount === 0) {
          res.status(200).json({
            message: 'No data.',
            data: [],
            dataCount: 0,
          });
          break;
        }

        if ((pageIndex - 1) * 4 >= dataCount) {
          throw new Error('Page does not exist!');
        }

        const dataFromDB: Array<IPerson> = await Person.find({})
          .skip((pageIndex - 1) * 4)
          .limit(4);

        if (!dataFromDB) {
          throw new Error('No data!');
        }

        res.status(200).json({
          message: 'Fetched data successfully',
          data: dataFromDB,
          dataCount,
        });
      } catch (error) {
        if (error instanceof Error)
          res.status(400).json({ message: error.message });
        else res.status(400).json({ message: 'Unexpected error' + error });
      }
      break;
    }
    case 'POST': {
      try {
        const person = await Person.create(
          req.body
        ); /* create a new model in the database */
        res
          .status(201)
          .json({ message: 'Created successfully!', data: person });
      } 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;
