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

// const errorHandler = (error, req, res, next) => {
//   if (!error) return next();

//   let statusCode = 400;
//   let errorMsg = "An unknown error occurred";

//   if (axios.isAxiosError(error)) {
//     // Axios Error
//     if (error.response) {
//       statusCode = error.response.status || 400;
//       errorMsg =
//         error.response.data?.message ||
//         error.response.statusText ||
//         "Remote server error";
//     } else if (error.request) {
//       errorMsg =
//         "No response from remote server. Please check your connection.";
//     } else if (error) {
//       // Axios setup error (e.g., invalid URL, timeout)
//       statusCode = error.status;
//       errorMsg = `Axios setup error: ${error.message}`;
//     } else {
//       errorMsg = `Axios setup error: ${error.message}`;
//     }
//   } else if (error instanceof Error) {
//     errorMsg = error.message;
//   } else if (error.code && typeof error.code === "string") {
//     // PostgreSQL errors, etc. (future use)
//     errorMsg = error.detail || error.message || error.toString();
//   } else if (typeof error === "string") {
//     errorMsg = error;
//   }

//   logger.error(`An error occurred: ${errorMsg}`);
//   return res.status(statusCode).json({ status: "failed", error: errorMsg });

//   // we may return this with more details in the future:
//   //   return res.status(statusCode).json({
//   //   status: "failed",
//   //   error: errorMsg,
//   //   isAxiosError: axios.isAxiosError(error),
//   // });
// };

// module.exports = errorHandler;

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

const errorHandler = (error, req, res, next) => {
  if (!error) return next();

  // Default fallback
  let statusCode = 500;
  let userMessage = "Internal Server Error"; // What user sees
  let isCustom = false; // Track if it's a custom error

  // ✅ If you explicitly throw a string or new Error("...") (your custom error)
  if (typeof error === "string") {
    userMessage = error;
    statusCode = 400;
    isCustom = true;
  } else if (error instanceof Error) {
    userMessage = error.message;
    statusCode = error.statusCode || 400;
    isCustom = true;
  } else if (axios.isAxiosError(error)) {
    logger.error(`[Axios Error]: ${error.message}`);
    // still treat as internal error unless it was thrown manually
    userMessage = `Remote server error:
    ${error.message}`;
    statusCode = error.response?.status || 500;
  }

  // ✅ Handle SQL/MariaDB errors (but do not expose to frontend)
  else if (error.code && error.sqlMessage) {
    logger.error(`[MariaDB Error]: ${error.sqlMessage}`);
    userMessage = "A database error occurred. Please contact support.";
    statusCode = 500;

    // ✅ Handle Node.js internal runtime errors
  } else if (
    error instanceof TypeError ||
    error instanceof ReferenceError ||
    error instanceof SyntaxError
  ) {
    logger.error(`[Node Error - ${error.name}]: ${error.message}`);
    userMessage = "An internal server error occurred.";
    statusCode = 500;

    // ✅ Any other unknown error
  } else {
    logger.error(`[Unknown Error]: ${error.message || error}`);
    userMessage = "An unexpected error occurred.";
    statusCode = 500;
  }

  return res.status(statusCode).json({
    status: "failed",
    error: userMessage,
  });
};

module.exports = errorHandler;
