function wantsImprovementJson(req) {
  const explicitFormat = String(req.get?.("x-lumi-response-format") || "").trim().toLowerCase();
  if (explicitFormat === "json") return true;
  if (req.xhr === true) return true;
  return req.accepts?.(["json", "html"]) === "json";
}

function sendImprovementResult(req, res, type, message, result = {}) {
  if (wantsImprovementJson(req)) {
    return res.status(type === "error" ? 400 : 200).json({
      success: type !== "error",
      message,
      result
    });
  }
  req.session.flash = { type, message };
  return res.redirect("/plugins/lumi_ai/improvement_center");
}

function sendImprovementError(req, res, status, message) {
  if (wantsImprovementJson(req)) {
    return res.status(status).json({
      success: false,
      error: message,
      message
    });
  }
  return res.status(status).render("error", {
    title: status === 404 ? "Feedback not found" : status === 400 ? "Invalid feedback action" : "Access denied",
    message
  });
}

module.exports = {
  wantsImprovementJson,
  sendImprovementResult,
  sendImprovementError
};
