const logger = require("./logger");

const errorHandler = (error, req, res, next) => {
  if (error) {
    // Check if the error is an instance of Error and has a message property
    if (error instanceof Error && error.message) {
      logger.error(`An error occured: ${error.message}`);
      res.status(400).json({
        status: "failed",
        error: error.message,
      });
    } else if (error instanceof Error) {
      logger.error(`An error occured: ${error}`);
      res.status(400).json({
        status: "failed",
        error,
      });
    } else if (error.code === "23505") {
      logger.error(`An error occured: ${error.detail}`);
      res.status(400).json({
        status: "failed",
        error: error.detail,
      });
    } else if (error.code === "23503") {
      logger.error(`An error occured: ${error.detail}`);
      res.status(400).json({
        status: "failed",
        error: error.detail,
      });
    } else if (error.code === "22P02") {
      logger.error(`An error occured: ${error.detail}`);
      res.status(400).json({
        status: "failed",
        error: error.detail,
      });
    } else if (error.code === "42703") {
      logger.error(`An error occured: ${error.message}`);
      res.status(400).json({
        status: "failed",
        error: error.message,
      });
    } else if (error.message) {
      logger.error(`An error occured: ${error.message}`);
      res.status(400).json({
        status: "failed",
        error: error.message,
      });
    } else {
      logger.error(`An error occured: ${error}`);
      res.status(400).json({
        status: "failed",
        error,
      });
    }
  } else {
    next();
  }
};
module.exports = errorHandler;
