const Home = require("../models/home");
const writeAuditLog = require("../audit/writeAuditLog");
const diffObject = require("../audit/diffObject");
const AUDIT_ACTIONS = require("../constants/auditAction");

// Helper to get FAQ data from Home model
const getFaqData = async () => {
  const home = await Home.findOne().sort({ updatedAt: -1 });
  if (!home || !home.faq) {
    return {
      heading: "",
      subheading: "",
      description: "",
      items: [],
      ctaButton: { label: "", href: "" },
    };
  }
  return home.faq.toObject ? home.faq.toObject() : home.faq;
};

// API to get FAQ data for frontend
exports.api = async (req, res) => {
  try {
    const faqData = await getFaqData();
    return res.json(faqData);
  } catch (err) {
    console.error("API Error:", err);
    res.status(500).json({ error: "Error loading FAQ data" });
  }
};

// Method for legacy route compatibility or internal use
exports.getFAQData = async (req, res) => {
  return exports.api(req, res);
};

// Render admin view
exports.index = async (req, res) => {
  try {
    const data = await getFaqData();
    // Ensure default structure if data is partial
    const safeData = {
      heading: data.heading || "",
      subheading: data.subheading || "",
      description: data.description || "",
      ctaButton: data.ctaButton || { label: "", href: "" },
      items: data.items || [],
    };

    const frontendUrl = process.env.FRONTEND_URL;

    res.render("admin/home/faq/index", {
      title: "FAQ Section Management",
      layout: "layouts/main",
      data: safeData,
      frontendUrl,
      currentPath: req.path,
      user: req.session.user,
    });
  } catch (error) {
    console.error("Error in FAQ index:", error);
    req.flash("error_msg", "An error occurred while loading the page");
    res.redirect("/admin/dashboard");
  }
};

// Update FAQ data
exports.update = async (req, res) => {
  try {
    const { heading, subheading, description, ctaLabel, ctaHref, items } =
      req.body;

    let parsedItems = [];
    if (items) {
      try {
        parsedItems = typeof items === "string" ? JSON.parse(items) : items;
      } catch (e) {
        console.error("Error parsing items JSON:", e);
        parsedItems = [];
      }
    }

    let home = await Home.findOne().sort({ updatedAt: -1 });
    if (!home) {
      home = new Home({});
    }

    // ✅ Capture BEFORE state
    const beforeData = home.faq
      ? JSON.parse(
          JSON.stringify(home.faq.toObject ? home.faq.toObject() : home.faq),
        )
      : {};

    const updatedFaqData = {
      heading: heading || "",
      subheading: subheading || "",
      description: description || "",
      ctaButton: {
        label: ctaLabel || "",
        href: ctaHref || "",
      },
      items: parsedItems.map((item) => ({
        question: item.question || "",
        answer: item.answer || "",
      })),
    };

    home.faq = updatedFaqData;
    await home.save();

    // ✅ Capture AFTER state
    const afterData = JSON.parse(JSON.stringify(updatedFaqData));

    // ✅ AUDIT LOGGING - FAQ Updated
    const changes = diffObject(beforeData, afterData);
    if (changes.length > 0) {
      await writeAuditLog({
        model: "Home",
        documentId: home._id,
        action: AUDIT_ACTIONS.UPDATE_FAQ,
        before: beforeData,
        after: afterData,
        changes,
        req,
      });
    }

    req.flash("success_msg", "FAQ section updated successfully");
    res.redirect("/admin/home/faq");
  } catch (err) {
    console.error("Error updating FAQ:", err);
    req.flash("error_msg", err.message || "Error updating FAQ");
    res.redirect("/admin/home/faq");
  }
};

// Placeholder methods to prevent route crashes if routes are not cleaned up immediately
exports.addFAQ = (req, res) =>
  res.status(404).json({ error: "Endpoint deprecated" });
exports.updateFAQItem = (req, res) =>
  res.status(404).json({ error: "Endpoint deprecated" });
exports.deleteFAQItem = (req, res) =>
  res.status(404).json({ error: "Endpoint deprecated" });
exports.addFAQSection = (req, res) =>
  res.status(404).json({ error: "Endpoint deprecated" });
exports.updateFAQSection = (req, res) =>
  res.status(404).json({ error: "Endpoint deprecated" });
exports.deleteFAQSection = (req, res) =>
  res.status(404).json({ error: "Endpoint deprecated" });
exports.reorderFAQSection = (req, res) =>
  res.status(404).json({ error: "Endpoint deprecated" });
exports.updateSidebarNav = (req, res) =>
  res.status(404).json({ error: "Endpoint deprecated" });
