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

const errorHandler = (err, req, res, next) => {
  logger.error({ message: err.message, url: req.url, method: req.method, userId: req.user?.id });

  if (err.code === "P2002") return res.status(409).json({ error: "Valor duplicado", field: err.meta?.target });
  if (err.code === "P2025") return res.status(404).json({ error: "Registro no encontrado" });

  const status = err.status || err.statusCode || 500;
  res.status(status).json({ error: status < 500 ? err.message : "Error interno del servidor" });
};

const notFound = (_req, res) => {
  res.status(404).json({ error: "Ruta no encontrada" });
};

module.exports = { errorHandler, notFound };
